#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Node
{
int data;
struct Node *next;
}Node,*PNODE;
void Delete(PNODE Head,int pos)//删除
{
int i=0;
PNODE p=Head;
while(p&&(i<pos-1))
{
p=p->next;
i++;
}
if(p==NULL||i>pos-1)
{
printf("错误\n");
exit(-1);
}
PNODE q=p->next;
p->next=q->next;
free(q);
q=NULL;
}
void insert(PNODE Head,int pos,int val)//添加
{
int i=0;
PNODE p=Head;
while((NULL!=p)&&(i<pos-1))
{
p=p->next;
i++;
}
if(p==NULL||i>pos-1)
{
exit(-1);
}
PNODE q=(PNODE)malloc(sizeof(Node));
q->data=val;
q->next=p->next;
p->next=q;
}
struct Node* create(int a)//建立链表
{
int i;
int val;
Node* Head=(Node*)malloc(sizeof(Node));
if(Head==NULL)
{
printf("Memory allocation failure");
exit(-1);
}
else
{
PNODE tail=Head;
Head->next=NULL;
printf("please input the length of list: ");
for(i=0;i<a;i++)
{
PNODE p=(PNODE)malloc(sizeof(Node));
if(p==NULL)
{
printf("memroy allocation failure");
exit(-1);
}
else
{
printf("please input the value of the %d list:",i+1);
scanf("%d",&val);
p->data=val;
tail->next=p;
p->next=NULL;
tail=p;
}
}
}
return Head;
}
void print(PNODE Head)//遍历输出链表
{
PNODE p;
if(!Head->next)
{
printf("the list is empty");
exit(-1);
}
p=Head->next;
while(p)
{
printf("%d\t",p->data);
p=p->next;
}
printf("\n");
}
struct Node* inter_link(struct Node* chain1,int
a,struct Node* chain2,int b)//链表合并
{
int temp;
struct Node*head,*p1,*p2,*pos;
if(a>=b){
head=p1=chain1;
p2=chain2->next;
}else{
head=p1=chain2;
p2=chain1->next;
temp=a;
a=b;
b=temp;
}
pos=head;
while(p2!=NULL)
{
p1=p1->next;
pos->next=p2;
pos=p2;
p2=p2->next;
pos->next=p1;
pos=p1;
}
return head;
}
void inversion(PNODE Head)//翻转倒置算法
{
PNODE p,q,pr;
p=Head->next;
q=NULL;
Head->next=NULL;
while(p)
{
pr=p->next;
p->next=q;
q=p;
p=pr;
}
Head->next=q;
}
void sortlist(struct Node *Head,int h)//排序算法
{
int i,j;
int swap;
struct Node *m,*n;
for(i=0,m=Head->next;i<h-1;i++,m=m->next)
{
for(j=i+1,n=m->next;j<h;j++,n=n->next)
{
if(m->data<n->data)
{
swap=m->data;
m->data=n->data;
n->data=swap;
}
}
}
printf("排序婉结果为:\n");
return ;
}
int main()//主函数
{
struct Node *Head,*tab;
int a,b,h;
scanf("%d",&a);
Head=create(a);
printf("this is the list:\n");
print(Head);
scanf("%d",&b);
tab=create(b);
print(tab);
inversion(Head);
printf("inverted list:\n");
print(Head);
printf("insert3:\n");
Head=inter_link(Head,a,tab,b);
print(Head);
h=a+b;
sortlist(Head,h);
print(Head);
insert(Head,3,999);
print(Head);
Delete(Head,3);
print(Head);
return 0;
}
下面是链表主要内容的完整实现
包阔建立链表、插入链表、删除链表、合并链表、倒置链表以及排序
以下使用c语言实现