完成过程可谓是艰辛,尤其是删除操作的各种情况!
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef int ElemType ;
typedef struct Node{
ElemType data ;
struct Node *next ;
}Lnode;
Lnode *create(int n)
{
Lnode *head , *p , *q ;
int i ;
head = (Lnode *)malloc(sizeof(Lnode)) ;
head->next = NULL ;
q = head ;
for(i = 0 ; i < n ; i ++)
{
p = (Lnode *) malloc(sizeof(Lnode)) ;
scanf("%d",&p->data) ;
q->next = p ;
p->next = NULL ;
q = p ;
}
return head ;
}
Lnode *get(Lnode *L , int i)
{
Lnode *p ;
int j = 0 ;
p = L ;
while(p->next != NULL && j < i) p = p->next , j ++ ;
if(i == j) return p ;
else return NULL ;
}
int insert(Lnode *L , int i , ElemType x)
{
Lnode *p , *q ;
int j = i - 1 ;
if(get(L , i - 1) == NULL)
{
printf("Insertion location invalid\n") ;
return 0 ;
}
else
{
p = get(L , i - 1) ;
q = (Lnode *) malloc(sizeof(Lnode)) ;
q->data = x ;
q->next = p->next ;
p->next = q ;
return 1 ;
}
}
Lnode *locate(Lnode *L , ElemType x)
{
Lnode *p ;
p = L->next ;
while(p != NULL)
{
if(p->data == x)
{
return p ;
}
else
{
p = p->next ;
}
}
return p ;
}
Lnode *deleteElem(Lnode *L , ElemType x)
{
Lnode *p , *q , *head ;
while(L->data == x) L = L->next ;
head = L ;
p = head ;
q = p->next ;
while(q != NULL)
{
if(q->data == x)
{
p->next = p->next->next ;
q = p->next ;
}
else
{
p = q ;
q = q->next ;
}
}
return head ;
}
void display(Lnode *L)
{
Lnode *p ;
p = L->next ;
while(p != NULL)
{
printf("%d\t",p->data) ;
p = p->next ;
}
puts("") ;
return ;
}
Lnode *merge(Lnode *La , Lnode *Lb )
{
display(La) ;
display(Lb) ;
Lnode *p , *head , *q;
head = (Lnode *) malloc (sizeof(Lnode)) ;
head->next = NULL ;
p = head ;
La = La->next , Lb = Lb->next ;
while(La != NULL && Lb != NULL)
{
if(Lb->data < La->data)
{
head->next = Lb ;
head = head->next ;
Lb = Lb->next ;
}
else
{
head->next = La ;
head = head->next ;
La = La->next ;
}
}
while(La != NULL)
{
head->next = La ;
head = head->next ;
La = La->next ;
}
while(Lb != NULL)
{
head->next = Lb ;
head = head->next ;
Lb = Lb->next ;
}
return p ;
}
int lengh(Lnode *L)
{
int res = 0 ;
Lnode *p ;
p = L->next ;
while(p != NULL)
{
res ++ ;
p = p->next ;
}
return res ;
}
void main()
{
Lnode *L , *La , *Lb , *Lc ;
int num = 0 ;
int mark , size ;
ElemType a ;
ElemType x ;
printf("Please input the num of elements\n") ;
scanf("%d",&num) ;
printf("Please input the elements to establish a linked list\n") ;
L = create(num) ;
printf("The list stored in linked from is\n") ;
display(L) ;
printf("Please input the location and element to be inserted\n") ;
scanf("%d%d",&mark,&x) ;
insert(L , mark , x) ;
display(L) ;
size = lengh(L);
printf("The size of the linked list is %d\n",size) ;
printf("Please input the element to be deleted\n") ;
scanf("%d",&a) ;
L = deleteElem(L , a) ;
display(L) ;
printf("Please input 2 ordered list\n") ;
La = create(num) ;
Lb = create(num) ;
Lc = merge(La , Lb) ;
display(Lc) ;
return ;
}