序言
本文主要包括:
(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=https://www.cnblogs.com/it1997/p/1;//一般不初始化資料 headNode->next=NULL; return headNode; } //創建結點 struct Node* createNode(int data){ struct Node* newNode=(struct Node*)malloc(sizeof(struct Node)); //初始化新結點 newNode->data=https://www.cnblogs.com/it1997/p/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; }
二、運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/116943.html
標籤:其他
下一篇:進制轉化相關問題
