#include <iostream> #include<bits/stdc++.h> using namespace std; class List; struct LinkNode { int data; LinkNode *link; LinkNode(LinkNode* ptr=NULL) { link=ptr; } LinkNode(const int item,LinkNode* ptr=NULL) { data=item; link=ptr; } }; class List { public: List() { first=new LinkNode; } void input(); void output(); friend void Union(List &a,List &b); int Length()const; int Search(int x); LinkNode *Locate(int i); int getData(int i); bool Insert(int i,int &x); bool Remove(int i,int &x); LinkNode* Sort(LinkNode* first); LinkNode *first; }; void List::input() { int x,data; cin>>x; for(int i=0; i<x; ++i) { cin>>data; LinkNode *newNode=new LinkNode(data); if(newNode==NULL) { cerr<<"存储分配失败!"<<endl; exit(1); } newNode->link=first->link; first->link=newNode; } } void List::output() { LinkNode *current=first->link; while(current!=NULL) { cout<<current->data<<endl; current=current->link; } } int List::Length()const//{1,2}A包含2个元素 { LinkNode *p=first->link; int count=0; while(p!=NULL) { p=p->link; count++; } return count; } int List::Search(int x) //返回2的位置是1,从1开始 { int k=1; LinkNode *current=first->link; while(current!=NULL) { if(current->data!=x) { current=current->link; k++; } else { break; } } if(current!=NULL) return k; else return k=0; } LinkNode *List::Locate(int i)//返回第1个的地址 { if(i<0) return NULL; LinkNode *current=first; int k=0; while(current!=NULL&&k<i) { current=current->link; k++; } return current; } int List::getData(int i)//得到第1个的值--2 { int x; LinkNode *current =Locate(i); x=current->data; return x; } bool List::Insert(int i,int &x) { LinkNode *current =Locate(i); if(current==NULL) return false; LinkNode *newNode=new LinkNode(x); if(newNode==NULL) { cerr<<"存储分配失败!"<<endl; exit(1); } newNode->link=current->link; current->link=newNode; return true; } bool List::Remove(int i,int &x) { LinkNode *current =Locate(i-1); if(current==NULL||current->link==NULL) return false; LinkNode *del=current->link; current->link=del->link; x=del->data; delete del; return true; } void Union(List &a,List &b) { int n=a.Length(),m=b.Length(),i,k,x; for(i=1; i<=m; ++i) { x=b.getData(i); k=a.Search(x); //cout<<k<<endl; if(k==0) { a.Insert(n,x); //cout<<a.first->link->data; n++; } } } LinkNode* List::Sort(LinkNode* first) { LinkNode* pNode1 = first; LinkNode* pNode2 = first; if(first == NULL) return NULL; for(; pNode1->link!=NULL; pNode1=pNode1->link) { for(pNode2=first; pNode2->link!=NULL; pNode2=pNode2->link) { if(pNode2->data>pNode2->link->data) { int temp = pNode2->data; pNode2->data = pNode2->link->data; pNode2->link->data = temp; } } } return first; } int main() { List a; a.input(); //a.output(); List b; b.input(); //b.output(); //cout<<endl; Union(a,b); //a.output(); a.Sort(a.first); a.output(); return 0; }
这是我们数据结构与算法的第一个实验,单链表的基本操作。
测试用例如下:
原文:https://www.cnblogs.com/moonlight1999/p/10779317.html