本文主要是介绍单向链表基础,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
单向升序链表的创建,结点插入,删除,逆转,合并
#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;
}
这篇关于单向链表基础的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!