#include<iostream>#include<stdlib.h>using namespace std;typedef struct _node{ int data; struct _node *next;}Node;//鏈表節(jié)點(diǎn)結(jié)構(gòu)。typedef struct{ Node *head; Node *end;}List;void add(List *list,int d){ Node *p=(Node*)malloc(sizeof(Node)); p->data=d; p->next=(list->head);//創(chuàng)建一個(gè)p指針,如果不需要循環(huán)鏈表p->next=NULL即可。 Node *last=list->head;//last指針作為遍歷指針。 if(last)//判斷邊界,鏈表內(nèi)是否有數(shù)據(jù)? { while((last->next)!=(list->head)) { last=last->next; } last->next=p; }else{ list->head=p; p->next=(list->head); } }void show(List *list){ if(list->head==NULL) { cout<<"nothing"<<endl; } else{ Node *p=(Node*)malloc(sizeof(Node)); p=list->head; do{ cout<<p->data; p=p->next; }while(p!=(list->head)); } }void remove(List *list,int plc){ if(list->head==NULL) { cout<<"NULL"; }else{ Node *q=(Node*)malloc(sizeof(Node)); Node *p=(Node*)malloc(sizeof(Node)); p=list->head; for(q=NULL;;q=p,p=p->next) //這里判斷條件為空,所以如果鏈表中沒有尋找數(shù)據(jù)是不會(huì)跳出循環(huán)的,如果需要跳出循環(huán)條件為將代碼參照show()里的遍歷方式,或者判斷q指針也是可以的。 { if(p->data==plc) { if(q)//防止鏈表中第一個(gè)節(jié)點(diǎn)為刪除節(jié)點(diǎn),此時(shí)需要判斷q的值,因?yàn)槟愕谝粋€(gè)節(jié)點(diǎn)前沒有節(jié)點(diǎn)了。 { q->next=p->next; }else{ list->head=p->next; } free(p); break; } } } }int main(){ List list; int n; int m; list.head=NULL; cin>>n>>m; for(int i=0;i<n;i++) { add(&list,i); } show(&list); remove(&list,2); cout<<endl; show(&list); return 0;}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注