求解答
代码如下:
#include<stdio.h>
#include<stdlib.h>
using namespace std;
//存储结构
typedef struct LNode{
int data;
struct LNode *next;
}LNode, *LinkList;
//头插法建表
LinkList creatlist()
{
int data; LinkList head; LNode *p;
head = NULL;
int n;
puts("请输入初始节点个数:");
scanf("%d",&n);
while(n--)
{
puts("请输入节点值:");
scanf("%d",&data);
p = (LNode *)malloc(sizeof(LNode));
p->data = data;
p->next = head;
head = p;
}
puts("节点创建完成!");
puts("");
return head;
}
//尾插法建表
LinkList creatlist_tail()
{
int data; LinkList head; LNode *p,*tail;
p = (LNode *)malloc(sizeof(LNode));
int n = 0;
printf("请输出节点数值:\n");
while(1)
{
scanf("%d",&data);
if(data == 0) break;
if(n == 0)
{
p->data =data;
head = p;
tail = p;
p->next = NULL;
n++;
}
else
{
p->data = data;
tail->next = p;
p->next = NULL;
tail = p;
n++;
}
p = (LNode *)malloc(sizeof(LNode));
}
return head;
}
//按序号查找
LNode *GetElem(LinkList head,int i)
{
int j = 0;
LNode *p = head;
while(p->next&&j<i)
{
p = p->next;
j++;
}
if(i == j) return p;
else return NULL;
}
//在序号为x的数之前插入
void InsertNode(LinkList head,int x,int e)
{
LNode *p,*q;
p = GetElem(head,x-1);
//检验找到的节点
if(p == NULL)
{
puts("position error");
return;
}
q = (LNode *)malloc(sizeof(LNode));
q->data = e;
q->next = p->next;
p->next = q;
}
//删除
void DeletNode(LinkList head,int x)
{
LNode *p,*q;
p = GetElem(head,x-1);
q = p->next;
p->next = p->next->next;
free(q);
}
//修改
void ChangeNode(LinkList head,int x,int e)
{
LNode *p;
p = GetElem(head,x);
p->data = e;
}
//遍历
void bianli(LinkList head)
{
LNode *h = head;
while(h!=NULL)
{
printf("%d ",h->data);
h = h->next;
}
puts("");
}
void sort(LinkList head1,LinkList head2,LinkList head3)
{
LNode *p1,*p2,*p3;
p1 = head1; p2 = head2;
head3 = head1;
p3 = head1;
while(p1&&p2)
{
if(p1->data<=p2->data)
{
p3->next = p1; p3 = p1; p3->next = NULL; p1 = p1->next;
}
else
{
p3->next = p2; p3 = p2; p3->next = NULL; p2 = p2->next;
}
}
p3->next = p1?p1:p2;
free(head2);
}
int main()
{
LinkList head = creatlist_tail();
printf("当前链表1所有节点:\n");
bianli(head);
printf("查找序号为0的节点:\n");
LNode *p = GetElem(head,0);
printf("%d",p->data);
puts("");
printf("在序号为2的节点前插入数值为7的节点:\n");
InsertNode(head,2,7);
bianli(head);
printf("删除当前序号为2的节点:\n");
DeletNode(head,2);
bianli(head);
printf("将序号为0的节点值改为8:\n");
ChangeNode(head,0,8);
bianli(head);
LinkList head2 = creatlist_tail();
printf("当前链表2所有节点:\n");
bianli(head2);
LinkList head3;
sort(head,head2,head3);
//bianli(head3);
puts("********************");
LNode *p3 = GetElem(head3,0);
printf("%d",p->data);
puts("");
return 0;
}
//1 2 3 4 5 0