include <stdio.h>
include <stdlib.h>
define ERROR -1
define OK 1
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
void Output(LNode *head){
while(head->next != NULL){
head = head->next;
printf("%d ", head->data);
}
printf("\n");
}
LNode createLink(LNode *head, int n){
LNode *p, *q;
int i;
head = p = (LNode *)malloc(sizeof(LNode));;
p->next = NULL;
printf("按照升序输入%d个数字:\n", n);
for(i = 0; i < n; i++){
q = (LNode *)malloc(sizeof(LNode));
scanf("%d", &q->data);
q->next = p->next;
p->next = q;
p = q;
}
Output(head);
return *head;
}
void FindLink(LNode *L, int num){
LNode *p;
p = L;
int i = 0;
while(p->data != num && p->next != NULL){
p = p->next;
i++;
}
if(p->data == num){
printf("find:%d,pos:%d\n", p->data, i);
}
else{
printf("nofind:%d\n", num);
}
}
int insertLink(LNode *L, int i, int num){
LNode *p, *q;
p = L;
int j = 0;
while(p && j < i-1){
p = p->next;
j++;
}
if(!p || j > i-1){
return ERROR;
}
q = (LNode *)malloc(sizeof(LNode));
q->data = num;
q->next = p->next;
p->next = q;
Output(L);
return OK;
}
int DeleLink(LNode *L, int i){
LNode *p, *q;
int j = 0;
p = L;
while(p->next && j < i-1){
p = p->next;
j++;
}
if(!(p->next) || j > i-1){
return ERROR;
}
q = p->next;
p->next = q->next;
free(q);
Output(L);
return OK;
}
void MergeList(LNode *La, LNode *Lb, LNode *Lc){
LNode *pa, *pb, *pc;
pa = La->next;
pb = Lb->next;
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;
free(Lb);
Output(Lc);
}
int main()
{
LNode la, lb, lc;
int i, num;
la = createLink(&la, 5);
printf("请输入要查找的数字:");
scanf("%d", &num);
FindLink(&la, num);
printf("请输入要插入的位置:");
scanf("%d", &i);
printf("请输入要插入的数字:");
scanf("%d", &num);
insertLink(&la, i, num);
printf("请输入要删除的位置:");
scanf("%d", &i);
DeleLink(&la, i);
lb = createLink(&lb, 6);
printf("合并后:");
MergeList(&la, &lb, &lc);
return 0;
}