大牛无视,小白代码。。。又是无聊的上机课......
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef struct node
{
int data;
struct node * next;
}node, *linklist;
//顺序建立链表
linklist creat(linklist &l , int n)
{
l = (linklist)malloc(sizeof(node));
linklist p, tail;
tail = l;
for(int i = 1; i <= n; i++)
{
p = (linklist)malloc(sizeof(node));
cin >> p->data;
p->next = NULL;
tail->next = p;
tail = p;
}
return l;
}
//逆序建立链表 算法2.10
void creat_l(linklist &l, int n)
{
l = (linklist)malloc(sizeof(node));
l->next = NULL;
linklist p;
for(int i = 1; i <= n; i++)
{
p = (linklist)malloc(sizeof(node));
cin >> p->data;
p->next = l->next; l->next = p;
}
}
//get i-th elem
int getelem(linklist l, int i)
{
linklist p;
p = l->next;
int j = 1;
while(p && j < i)
{
p = p->next;
++j;
}
if(!p || j > i) return 0;
int e = p->data;
return e;
}
// 插入 算法2.8
void insert(linklist &l, int i, int e)
{
linklist p = l;
int j = 0;
while(p && j < i-1)
{
p = p->next;
++j;
}
if(!p || j > i-1)
return;
linklist s;
s = (linklist)malloc(sizeof(node));
s->data = e;
s->next = p->next;
p->next = s;
delete(s);
}
//delete 算法2.9
int del(linklist &l, int i)
{
linklist p = l;
int j = 0;
while(p->next && j < i-1)
{
p = p->next; j++;
}
if(!(p->next) || j > i-1) return 0;
linklist q;
q = p->next;
int e = q->data;
p->next = q->next;
delete q;
return e;
}
//合并 算法2.11
void merge(linklist &la, linklist &lb, linklist & lc)
{
linklist pa = la->next, pb = lb->next, pc;
lc = pc = la;
while(pa && pb)
{
if(pa ->data < pb->data)
{
pc->next = pa;
pc = pa;
pa = pa->next;
}
else
{
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
}
//输出
void print(linklist l)
{
linklist p = l->next;
while(p)
{
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}
int main()
{
int n;
linklist l;
cout << "Creat a LinkList !" << endl;
cout << "Please input the length of the LinkList: " << endl;
cin >> n;
cout << "Pleast input the elem :" << endl;
creat(l, n);
int i;
print(l);
cout << "Please input the i-th number you want to get:" << endl;
cin >> i;
cout << getelem(l, i) << endl;
cout << "Please input the number you want to insert and the posion: " << endl;
int e;
cin >> i >> e;
insert(l, i, e);
print(l);
cout << "Pleast input the i-th number you want to delete(0 mains not find the number): " << endl;
int j;
cin >> j;
cout << del(l, j) << endl;
print(l);
linklist lb, lc;
cout << "Creat another linklist:" << endl;
cin >> n;
creat_l(lb, n);
print(lb);
merge(l, lb, lc);
print(lc);
return 0;
}