日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

链表(C语言)

發(fā)布時間:2025/10/17 编程问答 6 豆豆
生活随笔 收集整理的這篇文章主要介紹了 链表(C语言) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#include <stdio.h> #include <stdlib.h>#define number 5typedef int elemType;typedef struct List {elemType elem;struct List *next; }Node;//創(chuàng)建單鏈表 struct List *createList(int num) {Node *head,*p1,*p2;if((head=(Node*)malloc(sizeof(Node)))==NULL){printf("create error\r\n");exit(0);}head->elem=0;head->next=NULL;p1=head;int i;for(i=0;i<num;i++){if((p2=(Node*)malloc(sizeof(Node)))==NULL){printf("create error\r\n");exit(0);}p2->elem=i;p2->next=NULL;p1->next=p2;p1=p2;}return head; }//遍歷單鏈表 void displayList(Node *head) {Node *p1;if(head==NULL){printf("空鏈表\r\n");//exit(0);}else{for(p1=head->next;p1!=NULL;p1=p1->next){printf("%d\t",p1->elem);}printf("\r\n");} }//插入節(jié)點(diǎn) pos從1開始 void insertList(Node* head,elemType elem,int pos) {Node *p1,*p2;int i=1;p1=head;while(p1->next!=NULL){if(i>=pos)//pos=1break;p1=p1->next;i++;}if((p2=(Node*)malloc(sizeof(Node)))==NULL){printf("insert create rear error");exit(0);}if(p1->next!=NULL)//表中插入{p2->elem=elem;p2->next=p1->next;p1->next=p2;}else//在鏈表尾插入{p2->elem=elem;p2->next=NULL;p1->next=p2;} }//刪除結(jié)點(diǎn) pos從1開始 返回結(jié)點(diǎn)的值 elemType moveList(Node* head,int pos) {elemType temp;Node *p1,*p2;int i=1;p1=head;while(p1->next!=NULL){if(i>=pos){break;}i++;p1=p1->next;}p2=p1->next;if(p2->next==NULL)p1->next=NULL;elsep1->next=p2->next;return p2->elem; }//查找元素 返回元素位置 找不到返回-1 int searchList(Node* head,elemType elem) {Node* p1;p1=head;int i=1;while(p1->next!=NULL){if(p1->next->elem==elem){return i;}i++;p1=p1->next;}printf("找不到該元素\r\n");return -1; }//判斷鏈表是否為空 bool isEmptyList(Node* head) {return head==NULL;//||head->next==NULL; }//清除鏈表的所有節(jié)點(diǎn),包含頭節(jié)點(diǎn) struct List* clearList(Node* head) {Node *p1,*p2;p1=head;//int i=1;while(p1!=NULL){p2=p1->next;free(p1);p1=NULL;p1=p2;//printf("%d\t",i++);}head=NULL;//將所指的鏈表指針設(shè)為NULLreturn head; }int main() {Node *head;elemType temp;head=createList(number);displayList(head);insertList(head,8,3);displayList(head);insertList(head,9,7);displayList(head);temp=moveList(head,3);displayList(head);printf("移除:%d\r\n",temp);temp=moveList(head,6);displayList(head);printf("移除:%d\r\n",temp);temp=searchList(head,3);if(temp!=-1)printf("位置:%d\r\n",temp);temp=searchList(head,7);if(temp!=-1)printf("位置:%d\r\n",temp);if(!isEmptyList(head))printf("not empty\r\n");head=clearList(head);displayList(head);if(isEmptyList(head))printf("empty\r\n");return 0; }

總結(jié)

以上是生活随笔為你收集整理的链表(C语言)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。