資料結構連結串列 -- 查詢倒數第N個元素、中間元素、建立連結串列
#include<iostream>
using namespace std;
typedef int Status;
typedef int ElemType;
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef struct LNode{//define of LNode
ElemType data;
struct LNode *next;
}Lnode,*LinkList;
Status CreateList(LinkList &L,int n)//建立單鏈表
{
cout<<"要建立連結串列的資料個數:";
cin>>n;
L=new LNode();
L->next=NULL;
LinkList p;
p=NULL;
for(int i=n;i>=1;i--)
{
p=new LNode();
cin>>p->data;
p->next=L->next;
L->next=p;
}
cout<<"建立單鏈表成功!"<<endl;
return OK;
}
Status PrintList(LinkList &L)//遍歷單鏈表的資料元素
{
LinkList p;
p=L;
while(p->next!=NULL)
{
p=p->next;
cout<<p->data<<endl;
}
return OK;
}
Status PrintN(LinkList &L,int N){//查詢連結串列中倒數第N個節點的值
LinkList p;
LinkList q;
p=L;
q=new LNode();
q=NULL;
q=p->next;
cout<<"要查詢倒數第幾個資料:請輸入";
cin>>N;
int i=0;
int j=0;
int count=1;
while(count!=0){
if(q!=NULL)
{
j++;
q=q->next;
}
else
{
i=j-N;
for(int m=i;m>=0;m--){
p=p->next;
}
if(p)
{
cout<<p->data<<endl;
}
else
cout<<"不存在/n";
count=0;
}
}
return OK;
}
Status PrintMid(LinkList L){//找到中間節點
LinkList p;
LinkList q;
p=L;
q=new LNode();
q=p->next;
int i=0;
int j=1;
int count=1;
if(q->next!=NULL){
j+=1;
q=q->next;
if(q->next!=NULL){
j+=1;
while(q->next!=NULL){
q=q->next;
j++;
}
int m=j/2;
for(m=j/2;m>0;m--){
p=p->next;
}
cout<<p->data<<endl;
}
else{
cout<<"中間節點為:"<<endl;
cout<<q->data<<endl;
}
}
else{
cout<<"中間節點為:"<<endl;
cout<<q->data<<endl;
}
return OK;
}
void showmenu()
{
cout<<endl<<endl;
cout<<" *1: 初始化並建立單鏈表*"<<endl;
cout<<" *2: 遍歷連結串列資料*"<<endl;
cout<<" *3: 查詢倒數第N個數據*"<<endl;
cout<<" *4: 插入資料*"<<endl;
cout<<" *5: 查詢中間資料*"<<endl;
cout<<" *6: 刪除資料*"<<endl;
cout<<" *9: 離開*"<<endl;
cout<<" *請選擇....";
}
void main()//主函式
{
int select,number=1;
int N=3;
LinkList L;
L=NULL;
while(select!=9)
{
showmenu();
cin>>select;
switch(select)
{
case 1:
CreateList(L,number);
break;
case 2:
{
if (L)
{
PrintList(L);
}
else
{
cout<<"連結串列不存在!/n";
}
break;
}
case 3:
{
if (L)
{
PrintN(L,N);
}
else
{
cout<<"連結串列不存在!/n";
}
break;
}
case 5:
{
if (L)
{
PrintMid(L);
}
else
{
cout<<"連結串列不存在!/n";
}
break;
}
case 9:
break;
default:
cout<<"輸入錯誤,請重新輸入!"<<endl;
break;
}
}
}