C语言构建一个链表以及操作链表
生活随笔
收集整理的這篇文章主要介紹了
C语言构建一个链表以及操作链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>struct Node{int data;struct Node * pNext;
};struct Node * createList(void){int len; //存放有效節點的個數int i;int val; //用來臨時存放用戶輸入的節點的值struct Node * pHead = (struct Node *)malloc(sizeof(struct Node));if (NULL == pHead) {printf("分配失敗程序終止!\n"); exit(-1);}struct Node * pTail = pHead;pTail->pNext=NULL;printf("請輸入要生成鏈表的節點個數: len=");scanf_s("%d", &len);for (int i = 0; i < len; ++i){printf("請輸入第%d個節點的值:", i + i);scanf_s("%d",&val);struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));if (NULL == pNew) {printf("分配失敗程序終止!\n");exit(-1);}pNew->data = val;pTail->pNext = pNew;pNew->pNext = NULL;pTail = pNew;}return pHead;
};bool empty_list(struct Node * pHead) {if (pHead->pNext == NULL) {return true;}else{return false;}}void TraverseList(struct Node * pHead ) {if (empty_list(pHead)) { //判斷鏈表是否為空printf("鏈表為空");}else {//鏈表操作}//優化鏈表操作struct Node * p = pHead->pNext;while (NULL!=p){printf("%d\n", p->data);p = p->pNext;}return;
}int main(void) {struct Node * pHead=NULL; //頭指針(存放鏈表頭結點地址)pHead = createList(); //構建一個鏈表TraverseList(pHead); //操作鏈表
}
?
總結
以上是生活随笔為你收集整理的C语言构建一个链表以及操作链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大数运算(6)——大数阶乘(求位数)
- 下一篇: 大数运算(7)——大数阶乘(求阶乘)