单向链表基础

来源:互联网 发布:非农数据网址 编辑:程序博客网 时间:2024/05/02 00:35

单向升序链表的创建,结点插入,删除,逆转,合并

#include <iostream>#include <cstdio>using namespace std;template <typename Type>class Listline{public:typedef struct NODE{NODE(){next = NULL;}Type val;NODE *next;}Node;Listline():head(NULL), length(0){}~Listline(){Node *cur = head;while(cur){Node *tmp = cur->next;delete cur;cur = tmp;}}void Insert(const Type &val);void Delete(const Type &val);void Reverse();void Union(Listline &);void Display() const;int Size() const {return length;}private:Node *head;int length;};template <typename Type>void Listline<Type>::Insert(const Type &val){ // 升序插入Node **link = &head;Node *cur;while((cur = *link) != NULL && val > cur->val)link = &cur->next;Node *new_node = new Node;new_node->val = val;new_node->next = cur;*link = new_node;length++;}template <typename Type>void Listline<Type>::Delete(const Type &val){ // 删除链表中的第一个 valNode **link = &head;Node *cur;while((cur = *link) != NULL && val != cur->val)link = &cur->next;if(cur){*link = cur->next;delete cur;length--;}}template <typename Type>void Listline<Type>::Reverse(){ // 反转链表Node *cur = head->next;Node *per = head;while(cur){per->next = cur->next;cur->next = head;head = cur;cur = per->next;}}template <typename Type>void Listline<Type>::Union(Listline &li){ // 合并升序链表Node *cur1 = this->head;Node *cur2 = li.head;Node *new_head = cur1 ? cur1 : cur2;if(new_head == NULL)return;Node **link = &new_head;while(cur1 && cur2){if(cur1->val < cur2->val){*link = cur1;link = &cur1->next;cur1 = cur1->next;if(cur1 == NULL){*link = cur2;break;}}else{*link = cur2;link = &cur2->next;cur2 = cur2->next;if(cur2 == NULL){*link = cur1;break;}}}this->head = new_head;this->length += li.length;li.head = NULL;}template <typename Type>void Listline<Type>::Display() const{Node *cur = head;while(cur){cout << cur->val << ' ';cur = cur->next;}cout << endl;}void separate(){cout << "---------------------------------" << endl;}void test(){Listline<int> li1;Listline<int> li2;const int na = 8;const int nb = 6;int a[na] = {4, 2, -6, 0, 1, 5, 9, 7};int b[nb] = {3, -9, -3, 19, 90, 1};int c[na+nb];int clen = 0;for(int i = 0; i < na; i++){li1.Insert(a[i]);c[clen++] = a[i];}for(int i = 0; i < nb; i++){li2.Insert(b[i]);c[clen++] = b[i];}li1.Display();li2.Display();li1.Union(li2);li1.Display();separate();for(int i = 0; i < clen; i++){li1.Display();li1.Reverse();li1.Display();li1.Delete(c[i]);separate();}}int main(){test();return 0;}

0 0
原创粉丝点击