单链表的建立,插入和释放
生活随笔
收集整理的這篇文章主要介紹了
单链表的建立,插入和释放
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#include<iostream>
using namespace std;typedef struct node
{int data;struct node*next;
}Node, *List; //相當(dāng)于把strcut node另外命名為NOde和List* 指針類型List creatlist()
{Node* head, *p1, *p2; //建立一個鏈表,存儲數(shù)據(jù),p1和p2用于存儲,當(dāng)前數(shù)據(jù)和后一數(shù)據(jù)head = p2 = new Node;int num;cin >> num; while (-1 != num){p1 = new Node;p1->data = num;p1->next = NULL; //p1是新建的節(jié)點對象,存儲輸入的數(shù)據(jù)p2->next = p1; //p2指向新產(chǎn)生的對象p2 = p1; //p2轉(zhuǎn)移到鏈表的尾部cin >> num;}p2->next = NULL; //這一步必須的操作,,因為鏈表尾部指向一個空的對象return head;
}int getlistlength(List p)
{int lenlistlength = 0;while (p->next != NULL) //獲取鏈表的長度,主要是循環(huán)從鏈表的頭部開始進行循環(huán),知道節(jié)點指向一個空的對象{p = p->next;lenlistlength++;}return lenlistlength;
}
List insertnode(List p, int position, int element)
{int length = getlistlength(p);if (position<1 || position>length + 1){cout << "wrong position" << endl;exit(1);}Node *p1 = p->next; //想要插入一個數(shù)據(jù),必須得到插入位置的地址利用循環(huán)得到地址Node*p2 = p;int i;for (i = 0; i < position; i++){p2 = p1;p1 = p1->next; //得到插入位置的前一個對象和后一個對象的地址}Node* s = new Node; //建立一個新的對象存儲輸入的數(shù)據(jù)s->data = element;s->next = p1; p2->next = s; return p;
}void printlist(List p)
{while (p->next != NULL) //循環(huán)輸出,知道鏈表指向的對象是空為止{/*p = p->next;*/cout << p->next->data << endl; //因為第一個是鏈表的頭,沒存儲數(shù)據(jù)p=p->next;}
}void releaselist(List p) //利用遞歸的方法進行釋放每一個對象,,,迭代到最后一個對象,利用棧 思想進行釋放內(nèi)存
{if (NULL == p->next){delete p;}else{releaselist(p->next);delete p;}
}
int main()
{List head = creatlist();printlist(head);int position = 4;int element = 100;head = insertnode(head, position, element);releaselist(head);return 0;
}
總結(jié)
以上是生活随笔為你收集整理的单链表的建立,插入和释放的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二叉树(遍历、建立、深度)
- 下一篇: 双链表的建立、求长、定位、插入、删除、输