生活随笔
收集整理的這篇文章主要介紹了
C语言之单链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、學習要點:
1.指針在使用的時候一定要初始化;
初始化原因不明白見我博客:
https://blog.csdn.net/fyf18845165207/article/details/82954228
2.注意動態分配和釋放內存的函數malloc和delete;
二、程序代碼:
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct Node{ElemType data;struct Node *next;
}Node,*list;
list create_head();//確定鏈表頭結點
void create_list(list head,int n);//創造長度為n的單鏈表
void print(list head);//打印單鏈表
void delete_list(list head,int pos);//刪除單鏈表元素
list create_head(){list p;p=(list)malloc(sizeof(Node));if(p==NULL){printf("內存分配失敗");}else{p->next=NULL;return(p);}
}
void create_list(list head,int n){list p,temp;ElemType ch;p=head;while(n--){scanf("%d",&ch);temp=(list)malloc(sizeof(Node));temp->data=ch;temp->next=p->next;p->next=temp;p=temp;}
}
void print_list(list head){list p;p=head->next;//第一個節點while(p!=NULL){printf("%d\n",p->data);p=p->next;}}
void delete_list(list head,int pos){list p;list temp;p=head;for(int i=1;i<pos;i++){p=p->next;}temp=(list)malloc(sizeof(Node));temp=p->next;p->next=p->next->next;delete temp;
}
int main(){//主函數Node *head;head=create_head();create_list(head,5);printf("打印創建的單鏈表:\n");print_list(head);delete_list(head,3);printf("打印刪除第三個節點后的單鏈表:\n");print_list(head);system("pause");return 0;
}
三、程序運行結果:
總結
以上是生活随笔為你收集整理的C语言之单链表的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。