我们先来实现带头单链表的基本操作:
头文件:
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode*next;
}LT,*link;
void InitList(Link phead);//初始化
void InsertListfront(Link phead,ElemType x);//头插
void InsertListback(Link phead,ElemType x);//尾插
void InsertList(Link phead,ElemType x);//随机插入
void DeleteListfront(Link phead);//头删
void DeleteListback(Link phead);//尾删
void DeleteList(Link phead,ElemType x);//随机删除
void ReverseList(Link phead);//倒置
void PrintList(Link phead);//打印
声明函数的源文件:
#include"test.h"
void InitList(Link phead){
if(phead==NULL)
return ;
phead->next=NULL;
}
void InsertListfront(Link phead,ElemType x){
LT*newnode=(LT*)malloc(sizeof(LT));
if(newnode==NULL)
exit(-1);
else{
newnode->data=x;
newnode->next=phead->next;
phead->next=newnode;
}
}
void InsertListback(Link phead,ElemType x){
LT*newnode=(LT*)malloc(sizeof(LT));
if(newnode==NULL)
exit(-1);
else{
newnode->data=x;
newnode->next=NULL;
LT*tail=phead;
while(tail->next){
tail=tail->next;
}
tail->next=newnode;
}
}
void InsertList(Link phead,int pos,ElemType x){
LT*newnode=(LT*)malloc(sizeof(LT));
LT*P=phead->next;
if(newnode=NULL)
exit(-1);
else{
newnode->data=x;
for(int i=0;i<pos;i++)
p=p->next;
newnode->next=p->next;
p->next=newnode;
}
}
void DeleteListfront(Link phead,ElemType x){
if(phead->next==NULL){
printf("无元素删除\n");
exit(-1);
}
else{
LT*cur=phead->next;
phead->next=cur->next;
free(cur);
cur=NULL;
}
}
void DeleteListback(Link phead,ElemType x){
if(phead->next==NULL){
printf("无元素可删除\n");
exit(-1);
}
else{
LT*head=phead;
LT*tail=phead->next;
while(tail){
head=head->next;
tail=tail->next;
}
head->next=NULL;
free(tail);
tail=NULL;
}
}
void DeleteList(Link phead,ElemType x){
LT*head=phead;
LT*cur=NULL;
while(head->next){
if(head->next->data==x){
cur=head->next;
head->next=cur->next;
free(cur);
cur=NULL;
}
else
head=head->next;
}
}
反转链表就是倒置链表,有两个思路,第一个思路是将箭头指向相反的方向,第二个思路就是头插法。而每个思路的带头结点和不带头结点的操作也不同,下面我们来一一实现。
思路一:(带头结点的单链表)
void ReverseList(Linklist L){
ListNode*pre,*p=L->next,*r=p->next;
p->next=NULL;
while(r!=NULL){
pre=p;
p=r;
r=r->next;
p->next=pre;
}
L->next=p;//处理最后一个结点
}
思路二:头插法
void ReverseList(Link phead){
ListNode*p,*r;
p=phead->next;
phead->next=NULL;
while(p!=NULL){
r=p->next;
p->next=phead->next;
phead->next=p;
p=r;
}
}