7-3 sdut-C語言實驗-鏈表的結點插入
分數 20
全屏瀏覽
切換布局
作者?馬新娟
單位?山東理工大學
給出一個只有頭指針的鏈表和 n 次操作,每次操作為在鏈表的第 m 個元素后面插入一個新元素x。若m 大于鏈表的元素總數則將x放在鏈表的最后。
輸入格式:
多組輸入。每組數據首先輸入一個整數n(n∈[1,100]),代表有n次操作。
接下來的n行,每行有兩個整數Mi(Mi∈[0,10000]),Xi。
輸出格式:
對于每組數據。從前到后輸出鏈表的所有元素,兩個元素之間用空格隔開。
輸入樣例:
4
1 1
1 2
0 3
100 4
輸出樣例:
3 1 2 4
代碼長度限制
16 KB
時間限制
400 ms
內存限制
64 MB
棧限制
8192 KB
#include <stdio.h>
#include <stdlib.h>
struct node
{int a;struct node *next;
};//定義結構體類型;
int main()
{struct node *head,*p;int n,i;int x;while(~scanf("%d",&n)){head = (struct node*)malloc(sizeof(struct node));//要多組輸入,每一組輸入都要重新開辟一個頭結點;head -> next = NULL;for(i=0; i<n; i++){p = (struct node*)malloc(sizeof(struct node));p -> next = NULL;scanf("%d%d",&x,&p -> a);struct node *q = head -> next;struct node *qi = head;//定義兩個游動指針while(q&&x--)//尋找插入的位置;{q = q -> next;qi = qi -> next;}qi -> next = p;p -> next = q;//插入節點;}struct node *p;p = head -> next;while(p){if(p -> next){printf("%d ",p -> a);}else printf("%d\n",p -> a);p = p -> next;}}return 0;
}
#include <stdio.h> #include <stdlib.h>
這兩行代碼包含了標準的輸入輸出庫和標準庫,后者提供了動態內存分配的功能。
struct node { int a; struct node *next; };//定義結構體類型;
定義了一個名為node
的結構體,它包含一個整型數據a
和一個指向同類型結構體的指針next
。這個結構體用于表示鏈表中的每個節點。
int main() { // ... }
定義了main
函數,程序的執行從這里開始。
struct node *head, *p; int n, i; int x;
聲明了頭節點指針head
,新節點指針p
,循環計數器n
和i
,以及用于臨時存儲輸入值的x
。
while(~scanf("%d",&n)) { // ... }
使用while
循環讀取每組輸入的整數數量n
,直到輸入失敗(例如文件結束EOF)。~scanf
是一種技巧,用于檢查scanf
是否成功讀取了輸入。
head = (struct node*)malloc(sizeof(struct node)); head->next = NULL;
為鏈表的頭節點分配內存,并初始化頭節點的next
指針為NULL
。
for(i = 0; i < n; i++) { // ... }
循環n
次,每次讀取一對整數。
p = (struct node*)malloc(sizeof(struct node)); scanf("%d%d", &x, &p->a);
為新節點分配內存,并讀取一個整數到x
,然后將p->a
設置為讀取的值。
struct node *q = head->next; struct node *qi = head; while(q && x--) { // ... }
這段代碼試圖通過x--
來尋找插入新節點的位置,
qi->next = p; p->next = q;
將新節點p
插入到鏈表中qi
節點的后面。
p = head->next; while(p) { // ... }
遍歷鏈表并打印所有節點的數據。
return 0; }
main
函數返回0,表示程序正常結束。