jmu-ds-迴圈單鏈表的基本運算 (15 分)
阿新 • • 發佈:2019-01-05
實現迴圈單鏈表的基本運算:初始化、插入、刪除、求表的長度、判空、釋放。
(1)初始化迴圈單鏈表L,輸出(L->next==L)的邏輯值;
(2)依次採用尾插法插入元素:輸入分兩行資料,第一行是尾插法需要插入的字元資料的個數,第二行是具體插入的字元資料。
(3)輸出迴圈單鏈表L;
(4)輸出迴圈單鏈表L的長度;
(5)判斷迴圈單鏈表L是否為空;
(6)輸出迴圈單鏈表L的第3個元素;
(7)輸出元素a的位置;
(8)在第4個元素位置上插入‘w’元素;
(9)輸出迴圈單鏈表L;
(10)刪除L的第5個元素;
(11)輸出迴圈單鏈表L;
(12)釋放迴圈單鏈表L。
輸入格式:
兩行資料,第一行是尾插法需要插入的字元資料的個數,第二行是具體插入的字元資料。
輸出格式:
按照程式要求輸出
輸入樣例:
5
a b c d e
輸出樣例:
1
a b c d e
5
no
c
1
a b c w d e
a b c w e
個人估計後臺資料有點問題。。最後一個樣例顯示格式錯誤,但是題目中未提示某些特殊情況的具體格式。
#include <bits/stdc++.h> using namespace std; typedef struct LNode { char data; struct LNode *next; } LNode,*LinkList; int Create_Linklist(LinkList& p) { LinkList t,head; int n; cin>>n; head=p; for(int i=0;i<n;i++){ t=(LinkList)malloc(sizeof(LNode)); cin>>t->data; head->next=t; head=head->next; } head->next=p; return n; } void Print_Linklist(LinkList p) { LinkList head=p->next; while(head!=p){ if(head->next==p)cout<<head->data; else cout<<head->data<<" "; head=head->next; } } int Get_Length(LinkList p){ int cnt=0; LinkList head=p->next; while(head!=p){ cnt++; head=head->next; } return cnt; } char Get_Element(LinkList p){ int cnt=1; char e; int temp=3; if(Get_Length(p)<temp)temp=Get_Length(p); LinkList head=p->next; while(true){ if(cnt==temp){ e=head->data; return e; } cnt++; head=head->next; } } int Get_Count(LinkList p,char e){ int cnt=1; LinkList head=p->next; while(head!=p){ if(head->data==e){ return cnt; } cnt++; head=head->next; } return 0; } void Insert_Linklist(LinkList& p,int pos,char e){ if(pos<=0||Get_Length(p)<pos-1)return; int cnt=2; LinkList head=p->next,t; while(head!=p){ if(cnt==pos){ t=(LinkList)malloc(sizeof(LNode)); t->data=e; t->next=head->next; head->next=t; } cnt++; head=head->next; } } void Delete_Linklist(LinkList& p,int pos){ if(pos<=0||Get_Length(p)<pos)return; int cnt=2; LinkList head=p->next; while(head!=p){ if(cnt==pos){ LinkList t=head->next; head->next=t->next; free(t); break; } cnt++; head=head->next; } } void List_free(LinkList& p) { LinkList head,rear; head=p->next; while(head!=p){ rear=head; head=head->next; free(rear); } } int main() { LinkList l; l=(LinkList)malloc(sizeof(LNode)); l->next=l; if(l->next==l)cout<<1<<endl; else cout<<0<<endl; int cnt=Create_Linklist(l); Print_Linklist(l); cout<<endl; cout<<cnt<<endl; if(l->next==l)cout<<"yes"<<endl; else cout<<"no"<<endl; char e; e=Get_Element(l); cout<<e<<endl; cnt=Get_Count(l,'a'); cout<<cnt<<endl; Insert_Linklist(l,4,'w'); Print_Linklist(l); cout<<endl; Delete_Linklist(l,5); Print_Linklist(l); List_free(l); return 0; }