单链表(不带头结点)
生活随笔
收集整理的這篇文章主要介紹了
单链表(不带头结点)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
不帶頭結點的節點因為插入刪除的時候會改變或者刪除第一個節點,所以要引入二級指針進行一系列的操作
頭文件
#pragma once //不帶頭結點的單鏈表 typedef struct Node {int data;//數據Node * next;//存放下一個元素的地址 }Node; //初始化 void InitList(Node **ps); //頭插 bool Insert_Head(Node **ps,int val); //尾插 bool Insert_Tail(Node **ps,int val); //按位置插入 bool Insert_Pos(Node **ps,int pos,int val); //刪除某個節點 bool Delete_Node(Node **ps,int key); //刪除整個鏈表 bool Delete_List(Node **ps); //查找 Node *Search(Node *ps,int key); //鏈表長度 int GetLength(Node *ps); //打印鏈表的值 void Show(Node* ps);cpp文件
#include<iostream> #include<assert.h> #include"NoList.h" using namespace std;void InitList(Node* *ps) {assert(ps != NULL);*ps = NULL; }static Node* BuyNode(int val) {Node *pnewnode = new Node();pnewnode->data = val;pnewnode->next = NULL;return pnewnode; } bool Insert_Head(Node* *ps,int val) {assert(ps != NULL);Node* pnewnode = BuyNode(val);pnewnode->next = *ps;*ps = pnewnode;return true; }bool Insert_Tail(Node* *ps,int val) {assert(ps != NULL);Node* pnewnode = BuyNode(val);Node* pTail = *ps;if(pTail == NULL){*ps = pnewnode;//}else{ while(pTail->next != NULL){pTail = pTail->next;}pTail->next = pnewnode;}return true; }bool Insert_Pos(Node* *ps,int pos,int val) {assert(ps != NULL);Node * q = *ps;for(int i = 0;i<pos;i++){q = q->next;}Node *p =BuyNode(val);p->next = q->next;q->next = p;return true; }bool Delete_Node(Node* *ps,int key) {assert(ps != NULL);Node* p = Search(*ps,key);if(p == NULL){return false;}//刪除的節點是第一個節點也是最后一個節點if(p == *ps){delete p;p = NULL;/ps = NULL;/}//刪除的節點不是尾結點else if(p->next != NULL){Node * q = p->next;p->data = q->data;p->next = q->next;delete q;q = NULL;}//節點有很多,刪除的節點是尾結點else if(p ->next == NULL){Node* q = *ps;for(;q->next!= NULL;q = q->next);/*q ->next = NULL;q->next ->data = NULL;delete (q->next);*/q ->next = NULL;delete (q->next);p = NULL;}return true; }bool Delete_List(Node* *ps) {assert(ps != NULL);Node* p;//Node* q = p;while(*ps != NULL){p = *ps;*ps = p->next;delete p;}return true; }Node* Search(Node* ps,int key) {assert(ps != NULL);Node * q = ps;while(q != NULL){if(key == q->data){return q;}q = q->next;}return NULL; }int GetLength(Node *ps) {assert(ps != NULL);int length = 0;for(Node* q = ps;q!= NULL;q = q->next){length++;}return length; }void Show(Node* ps) {for(Node *q = ps;q!= NULL;q= q->next){cout << q->data << " " ;}cout <<endl; }主函數
#include<iostream> #include<assert.h> #include"NoList.h" using namespace std;int main() {Node* head;InitList(&head);/*for(int i = 0;i<10;i++){Insert_Head(&head,i);}*/for(int i = 0;i<10;i++){Insert_Tail(&head,i,i);}Show(*&head);cout << GetLength(head) << endl;Insert_Pos(&head,5,111);Show(*&head);cout << GetLength(head) << endl;Delete_Node(&head,5);Show(head);cout << GetLength(head) << endl;Delete_List(&head);Show(head);return 0; }?
總結
以上是生活随笔為你收集整理的单链表(不带头结点)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Win10怎么改网络服务器账号,win1
- 下一篇: 单片机模数转换实验c语言程序,单片机实验