版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lishang6257/article/details/69729577
基本内容
本例实现了单链表的创建,节点的插入,删除,以及链表排序,同时还实现了合并两个单链表
啥都不说了,直接贴上去
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <stdexcept>
using namespace std;
typedef struct lnode{
string data;
lnode* next;
}Lnode,* List;
//带头结点的单链表
int ListCreate(List L)
{
L->next = NULL;
string c; cin >> c;
List p = L;
try{
while(c != "#"){
List NewNode = new Lnode;
if(!NewNode) throw runtime_error("New Node can't be created correctly");
NewNode->data = c;
NewNode->next = 0;
p->next = NewNode;
p = p->next;
cin >> c;
}
}
catch(runtime_error err){
cout << err.what() << endl;
exit(1);
}
return 0;
}
int ListInsert(List L,string c,int n)
{
if(c == "#") {
cerr << "can't insert empty node!\n";
exit(1);
}
try{
List p = L;
int temp = 1;
while(p->next && temp < n){
temp ++;
p = p->next;
}
if(temp < n) throw out_of_range("out of range");
else {
List NewNode = new Lnode;
NewNode->data = c;
NewNode->next = p->next;
p->next = NewNode;
}
}
catch(out_of_range err){
cerr << err.what() << endl;
exit(1);
}
return 0;
}
int ListLength(List L)
{
int length = 0;
List p = L;
while(p->next){
length ++;
p = p->next;
}
return length;
}
int ListSort(List L) // increase
{
int n = ListLength(L);
List p = L;
string temp;
for(int j = 1; j < n + 1; j++)
{
p = L;
for(int i = 0; i < n + 1-j; i++)
{
if(p->data > p->next->data)
{
temp = p->data;
p->data = p->next->data;
p->next->data = temp;
}
p = p->next;
}
}
}
int ListPrint(const List L)
{
List p = L->next;
if(!p) {
cerr << "List is empty!\n";
return 1;
}
while(p){
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int ListDelete(List L,int n)
{
try{
List p = L;
int temp = 1;
while(p->next && temp < n){
temp ++;
p = p->next;
}
if(temp < n) throw out_of_range("out of range!\n");
List tmp = p->next;
p->next = tmp->next;
delete tmp;
}catch(out_of_range err){
cout << err.what() << endl;
exit(1);
}
return 0;
}
List ListUnion(List &NewList,List L1,List L2)
{
//List NewList = new Lnode;
NewList->next = NULL;
List p = L1->next,q = L2->next,New = NewList;
while(p && q){
if(p->data < q->data) {
List temp = new Lnode;
temp->next = NULL;
temp->data = p->data;
New->next = temp;
New = New->next;
p = p->next;
}
else{
List temp = new Lnode;
temp->next = NULL;
temp->data = q->data;
New->next = temp;New = New->next;
q = q->next;
}
}
while(p){
List temp = new Lnode;
temp->next = NULL;
temp->data = p->data;
New->next = temp;New = New->next;
p = p->next;
}
while(q){
List temp = new Lnode;
temp->next = NULL;
temp->data = q->data;
New->next= temp;New = New->next;
q = q->next;
}
return NewList;
}
int main()
{
List L1 = new Lnode;
List L2 = new Lnode;
//string c = 't';
ListCreate(L1);
ListSort(L1);
ListPrint(L1);
ListCreate(L2);
ListSort(L2);
ListPrint(L2);
List NewList = new Lnode;
ListUnion(NewList,L1,L2);
//cout << ListLength(L) << endl;
ListPrint(NewList);
return 0;
}
// 123#456#