標題 C語言兩種方式創建鏈表(頭插法與尾插法)
……不多解釋了,都在代碼注釋里
1.頭插法
//頭插法創建鏈表
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}Node;
int main()
{
Node *head,*p,*q,*t;
head=(Node*)malloc(sizeof(Node));//創建頭結點
head->next=NULL;//初始化為空鏈表
int a,n;//要輸入的數以及要創建的結點個數
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a;
p=(Node *)malloc(sizeof(Node));
p->data=a;;
p->next=head->next;//頭插法類似于插入排序,將原本頭結點指向的內容賦值給要插入的結點的后繼指標
head->next=p;//再使得頭結點指向要插入的結點
//每一次新插入的結點都在頭結點的后面,所以輸出順序和輸入順序是逆序
}
t=head->next;//從首結點處開始遍歷
while(t!=NULL)
{
cout<<t->data<<" ";
t=t->next;
}
cout<<endl;
}
運行結果:

2.尾插法
//尾插法創建鏈表
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}Node;
int main()
{
Node *head,*p,*q,*t;
head=(Node*)malloc(sizeof(Node));//創建頭結點
head->next=NULL;//初始化為空鏈表
int a,n;//要輸入的數以及要創建的結點個數
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a;
//動態申請一個空間用于存放結點
p=(Node*)malloc(sizeof(Node));
p->data=a;;
p->next=NULL;//設定當前結點的下一個結點為空
if(head->next==NULL)
head->next=p;//如果這是第一個創建的結點,則將頭結點的后繼指標指向當前結點
else
q->next=p;//如果不是,則將上一個結點的后繼指標指向當前結點
q=p;//指標q也必須指向當前結點,尾插法的關鍵
}
t=head->next;//從首節點處開始遍歷輸出
while(t!=NULL)
{
cout<<t->data<<" ";
t=t->next;
}
cout<<endl;
}
運行結果

以上內容若有錯誤或需要改進之處,歡迎在評論區提出,共同進步,(▽)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/264536.html
標籤:其他
