代碼:
/* *帶頭節點的單鏈表 */ #include<iostream> #include<stdlib.h> using namespace std; typedef struct ListNode { int data; struct ListNode* next; } Node,*PNode; //新建結點,num表示結點個數 PNode NewNode(int num) { //新建頭結點 PNode head=(PNode)malloc(sizeof(Node)); if(head==NULL) { cout<<"頭節點內存分配失敗!"; exit(0); } PNode temp=head; temp->next=NULL; for(int i=0; i<num; i++) { //當前結點的數據 int num; cin>>num; //新節點 PNode node=(PNode)malloc(sizeof(Node)); if(node==NULL) { cout<<"節點內存分配失敗!"; exit(0); } node->data=num; temp->next=node; temp=node;//使temp指向新建結點 } return head;//返回頭結點 } //刪除結點,temp表示刪除鏈表的第幾個結點 void Free(PNode node,int temp) { int num=1; while(temp!=num) { node=node->next; num++; } node->next=node->next->next; } //在尾部插入結點,temp表示插入的數據 void Insertoftail(PNode node,int temp) { while(node->next!=NULL)//注意判斷條件是node->next!=NULL;指向最后一個結點就停止 { node=node->next; } PNode New=(PNode)malloc(sizeof(Node)); if(New==NULL) { cout<<"節點內存分配失敗!"; exit(0); } New->data=temp; node->next=New; } //根據鏈表及數據,查找所在位置,只能查找第一個找到的 void Search(PNode node,int temp) { node=node->next; int num=0; while(node!=NULL) { num++; if(node->data==temp) { cout<<"您查找的數字"<<temp<<"在"<<num<<"位"<<endl; return; } node=node->next; } cout<<"未找到!"<<endl; } //輸出鏈表數據 void Printf(PNode node) { node=node->next;//頭節點需要跳過 while(node!=NULL) { cout<<node->data<<" "; node=node->next; } cout<<endl; } int main() { ListNode* head=NewNode(7);//新建長度為7的鏈表,逐個輸入數據 Printf(head);//輸出當前鏈表數據 Search(head,8);//查找數據為8的結點 Insertoftail(head,99);//在尾部插入數據為99的結點 Printf(head);//輸出當前鏈表數據 Free(head,1);//刪除第一個結點 Printf(head);//輸出當前鏈表數據 return 0; }
實驗截圖: