原blog被 誤刪TAT 大寫的尷尬?。。?!
數據結構上機測試2-1:單鏈表操作A PRoblem Description 輸入n個整數,先按照數據輸入的順序建立一個帶頭結點的單鏈表,再輸入一個數據m,將單鏈表中的值為m的結點全部刪除。分別輸出建立的初始單鏈表和完成刪除后的單鏈表。 Input 第一行輸入數據個數n; 第二行依次輸入n個整數; 第三行輸入欲刪除數據m。 Output 第一行輸出原始單鏈表的長度; 第二行依次輸出原始單鏈表的數據; 第三行輸出完成刪除后的單鏈表長度; 第四行依次輸出完成刪除后的單鏈表數據。 Example Input
10 56 25 12 33 66 54 7 12 33 12 12
Example Output
10 56 25 12 33 66 54 7 12 33 12 7 56 25 33 66 54 7 33
#include<stdio.h>#include<string.h>#include<stdlib.h>struct node{ int data; struct node *next;};int main() { int n, count, key; struct node *head, *p, *q, *t; head = (struct node *)malloc(sizeof(struct node)); head -> next = NULL; q = head; scanf("%d",&n); count = n; while(n -- ) //建立順序鏈表 { p = (struct node*)malloc(sizeof(struct node)); scanf("%d",&p -> data); p -> next = NULL; q -> next = p; q = p; } p = head -> next; scanf("%d",&key); printf("%d/n",count); p = head -> next; while (p) { printf("%d",p -> data); if (p ->next !=NULL) printf(" "); else printf("/n"); p = p -> next; } p = head; q = p; while(p) // 刪除重復元素 { while(q->next) { if(q->next->data == key) { t = q->next; q->next = t->next; free(t); count--; } else q = q->next; } p = p->next; q = p; }printf("%d/n",count); p = head -> next; while (p) //輸出 { printf("%d",p -> data); if (p ->next !=NULL) printf(" "); else printf("/n"); p = p -> next; } return 0; }新聞熱點
疑難解答