#include<iostream>#include<stdlib.h>using namespace std;typedef struct _node{ int data; struct _node *next;}Node;//鏈表節點結構。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);//創建一個p指針,如果不需要循環鏈表p->next=NULL即可。 Node *last=list->head;//last指針作為遍歷指針。 if(last)//判斷邊界,鏈表內是否有數據? { 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) //這里判斷條件為空,所以如果鏈表中沒有尋找數據是不會跳出循環的,如果需要跳出循環條件為將代碼參照show()里的遍歷方式,或者判斷q指針也是可以的。 { if(p->data==plc) { if(q)//防止鏈表中第一個節點為刪除節點,此時需要判斷q的值,因為你第一個節點前沒有節點了。 { 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;}
新聞熱點
疑難解答