序言
本文主要包括:
(1)單鏈表的創建
(2)創建結點
(3)打印結點
(4)鏈表的插入【頭插法】
(5)鏈表的刪除【指定位置刪除】
適合新手初步認識學習單鏈表的基本操作
一、代碼:
#include <stdio.h> #include <stdlib.h> #include<string.h> //結構體----結點由數據域+指針域構成 struct Node { int data;//數據域 struct Node* next;//指針域 }; //創建鏈表(表頭) struct Node* createList(){ struct Node* headNode=(struct Node*)malloc(sizeof(struct Node)); //headNode 成為了結構體變量 //變量使用前必須初始化 //headNode->data=1;//一般不初始化數據 headNode->next=NULL; return headNode; } //創建結點 struct Node* createNode(int data){ struct Node* newNode=(struct Node*)malloc(sizeof(struct Node)); //初始化新結點 newNode->data=data; newNode->next=NULL; return newNode; } //打印結點(遍歷結點) void printList(struct Node* headNode ) { struct Node* pMove=headNode->next;//打印指針指向頭結點下一個結點 while(pMove) { printf("%d\t",pMove->data); pMove=pMove->next; } printf("\n"); } //鏈表的插入:插入結點---插入那個鏈表、插入結點的數據是多少 void insertNodeByHead(struct Node* headNode,int data){ //1、創建一個插入結點 struct Node* insertNode=createNode(data); //調用createNode方法創建一個新的結點 insertNode->next=headNode->next; headNode->next=insertNode; } //鏈表的刪除:指定的位置刪除 ---刪除那個鏈表、刪除的數據是多少 void deleteNodeByAppoin(struct Node* headNode,int posData) { struct Node* posNode=headNode->next; struct Node* posNodeFront=headNode; if(posNode==NULL) printf("鏈表為空!"); else{ while(posNode->data!=posData){ posNodeFront=posNode; posNode=posNodeFront->next; if(posNode==NULL){ printf("無法找到指定位置"); return; } } posNodeFront->next=posNode->next; free(posNode); } } int main() { struct Node* list=createList();//創建一個名為list的鏈表 printf("插入前鏈表中的數據:\n"); printList(list); printf("插入后鏈表中的數據:\n"); insertNodeByHead(list,3);//向鏈表list插入數據---3 insertNodeByHead(list,2);//向鏈表list插入數據---2 insertNodeByHead(list,1);//向鏈表list插入數據---1 printList(list); //打印鏈表 list printf("刪除后鏈表中的數據:\n"); deleteNodeByAppoin(list,2);//刪除鏈表中數據為2的 printList(list); system("pause"); return 0; }