单链表--键盘输入、插入、删除、查询、输出
生活随笔
收集整理的這篇文章主要介紹了
单链表--键盘输入、插入、删除、查询、输出
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
通過鍵盤讀入數據,創建一只帶有頭點的單鏈表。要求能夠實現求單鏈表的長度,查詢單鏈表中指定位置上的節點信息,能夠進行節點的插入、刪除、查詢、輸出操作
# include "stdio.h" # include "stdlib.h" /*構造鏈表節點的數據類型*/ struct Node {int data;struct Node *next; }; /*對鏈表進行初始化操作*/ struct Node *InitList(struct Node *L) {struct Node *head = NULL;head = (struct Node *)malloc(sizeof(struct Node));if(! head){return 0;}head->next=NULL;L = head;return L; } /*求鏈表中節點的個數,即鏈表長度*/ int ListLength(struct Node *L) {struct Node *p = NULL;int count = 0;p = L;while(p->next){count++;p = p->next;} return count; } /*創建鏈表,將新生成的節點插入到鏈表的表頭*/ struct Node *CreatList(struct Node *L, int n) {int i;struct Node *p = NULL;for(i=n; i>0; i--){/*將新生成的節點插入到鏈表中*/p = (struct Node *)malloc(sizeof(struct Node));scanf("%d",&p->data);p->next = L->next;L->next = p;}return L;} /*對鏈表進行節點的插入操作*/struct Node *ListInsert(struct Node *L, int i, int e){int j = 0;struct Node *s = NULL, *p = NULL;p = L;while(p&&j<i-1){p = p->next;j++;}if(!p||j>i-1){printf("輸入的位置不合法!\n");return L;}/*生成一個新的節點s*/s = (struct Node *)malloc(sizeof(struct Node));s->data = e;/*節點的后插操作*/s->next = p->next;p->next = s;return L; }/*對鏈表進行節點的刪除操作*/struct Node *ListDelete(struct Node *L, int i){int j;struct Node *q = NULL, *p = NULL;p = L;j = 0; /*查詢指定位置上的節點*/while(p->next && j<i-1){p = p->next;j++;} if(!(p->next) || j>i-1){printf("輸入的位置不合法!\n");return L;}/*刪除指定的節點*/q = p->next;p->next = q->next;free(q);return L; }/*對鏈表中的節點進行查詢操作*/int GetElem(struct Node *L, int i){int j,e;struct Node *p = NULL;if(i<1 || i>ListLength(L)){printf("輸入的位置不合法!\n");return 0;} p = L->next;j = 1;while(j<i){p = p->next;j++;}e = p->data;printf("第%d個元素的數據為%d\n",i,e); }/*鏈表的操作*/void menu(){printf("**************************目錄************************\n");printf("輸出這只單鏈表 1\n");printf("在單鏈表中插入一個新節點 2\n");printf("在單鏈表中刪除指定節點 3\n");printf("查詢單鏈表中的節點 4\n");printf("退出 0\n"); printf("******************************************************\n");} /*主程序*/int main(){int n,m,i,e;struct Node *L = NULL, *p = NULL; L = InitList(L);printf("請輸入元素個數");scanf("%d",&n);printf("依次輸入%d個元素的數據(空格隔開):",n);L = CreatList(L,n);do{printf("\n\n");menu();printf("請輸入你的選擇:");scanf("%d",&m);switch(m){case 1:printf("這只單鏈表為:");p = L->next;while(p!=NULL){printf("%d->",p->data);p = p->next;}printf("\b\b\b\b");printf("\n");break;case 2:printf("依次輸插入位置和數據元素(空格隔開):");scanf("%d %d",&i,&e);L = ListInsert(L,i,e);break;case 3:printf("輸入需要刪除的元素的位置:");scanf("%d",&i);L = ListDelete(L,i);break;case 4:printf("輸入需要查詢元素的位置:");scanf("%d",&i);GetElem(L,i);break;case 0:printf("退出\n");break;default:printf("輸入錯誤!\n");} }while(m!=0);return 0;}總結
以上是生活随笔為你收集整理的单链表--键盘输入、插入、删除、查询、输出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java期末复习——ch02基本类型(进
- 下一篇: LeetCode----13. 罗马数字