C語言 鏈表
阿新 • • 發佈:2018-04-30
eof lse 結點 nsf char -s light stx void
鏈表示意圖
C語言 鏈表
鏈表**結點:**每個空間采用動態數據分配,,每個數據空間保存一個數據,可以根據需求分配數據空間數,而每個數據空間就叫做一個結點。每個結點結構中,我們定義一個成員存放下一個結點的首地址,用於存放下一個結點的成員,這個稱為指針域
**鏈表:**第一個結點的指針域存放下一個結點的首地址,以此內推一直到最後一個結點,最後一個結點的指針域指向Null。
鏈表示意圖
第0個結點稱為頭結點,沒有數據只存放第一結點的首地址
每個結點的都是同一種數據結構
struct Node{ int data; struct student *next; }Node,*PNode;
鏈表的基本操作:
- 鏈表的創建
- 鏈表的判斷
- 鏈表的長度獲取
- 鏈表的插入
- 鏈表的刪除
- 鏈表的遍歷
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<stdbool.h>
#define LEN sizeof(struct Node)
typedef struct Node{
int data;
struct Node *pnext;
}Node, *PNode;
/*創建鏈表:pHead為頭結點,pTail為尾結點,pNew為新創建的結點*/
PNode creatList(void){
PNode pHead, pTail, pNew;
int n, i;
pHead = (PNode)malloc(LEN);
pHead->pnext = NULL;
pTail = pHead;
printf("請輸入鏈表的長度\n");
scanf("%d",&n);
for(i = 0; i < n; i++){
pNew = (PNode)malloc(LEN);
pNew->pnext = NULL;
printf("請輸入第%d個鏈表的值\n", i+1);
scanf("%d" , &pNew->data);
pTail->pnext = pNew;
pTail = pNew;
}
return pHead;
}
/*鏈表的判斷:判斷鏈表是不是為空*/
bool isempty(PNode pHead){
if(pHead->pnext == NULL)
return true;
else return false;
}
/*鏈表的長度:獲取鏈表的長度*/
int list_num(PNode pHead){
int num = 0;
PNode p;
p = pHead->pnext;
while(p != NULL){
num+=1;
p = p->pnext;
}
return num;
}
/*鏈表的遍歷:輸出鏈表所有的數據*/
void traversal(PNode pHead){
PNode p;
p = pHead->pnext;
while(p != NULL){
printf("%d\n", p->data);
p = p->pnext;
}
}
/*鏈表的插入:插入的位置和數據需要提供*/
bool insert(PNode pHead, int val, int pos){
PNode p, pNew;
int i = 1;
p = pHead->pnext;
while(p != NULL){
if(i == pos){
pNew = (PNode)malloc(sizeof(LEN));
pNew->data = val;
pNew->pnext = p->pnext;
p->pnext = pNew;
printf("插入成功\n");
return true;
}
p = p->pnext;
i++;
}
printf("插入位置超過鏈表實際大小\n");
return false;
}
/*鏈表的刪除:*/
bool delete(PNode pHead, int pos){
int i;
PNode p, tmp;
p = pHead;
for(i=1; p!=NULL && i < pos; i++)
p = p->pnext;
if(p == NULL){
printf("刪除錯誤\n");
return false;
}
tmp = p;
p = p->pnext;
tmp->pnext = p->pnext;
free(p);
return true;
}
int main(int argc, char const *argv[])
{
PNode pHead;
pHead = creatList();
if(isempty(pHead))
printf("鏈表為空\n");
printf("鏈表的長度為:%d\n",list_num(pHead));
traversal(pHead);
//insert(pHead,55,1);
delete(pHead,2);
traversal(pHead);
return 0;
}
C語言 鏈表