单向链表在数据结构中比较常见,要求实现单向链表的反转,如下图所示:
反转前:
反转后:
C++代码如下:
#include <stdio.h>
#include <stdlib.h>
struct list{
int var;
struct list *next;
};
//反转单向链表
void reversal(struct list* &head)
{
struct list *p1,*pre,*after;
p1=head;
pre=head;
head=head->next;
while(head){
after=head->next;
head->next=pre;
pre=head;
if(after == NULL){
break;
}
head=after;
}
p1->next = NULL;
}
int main(){
int a[]={1,5,7,8,9,2,4,6,8,9,10,13,16,0};
struct list *head,*p1,*p2;
//创建单向链表
head=(struct list *)malloc(sizeof(struct list));
head->var=a[0];
head->next=NULL;
p1=head;
for(int i=1;i<sizeof(a)/sizeof(int);i++){
head->next=(struct list *)malloc(sizeof(struct list));
head=head->next;
head->var=a[i];
head->next=NULL;
}
head=p1;
//打印单向链表
while(p1){
printf("%2d ",p1->var);
p1=p1->next;
}
printf("\n");
//反转单向链表
reversal(head);
//打印反转后的单向链表
p1=head;
while(p1){
printf("%2d ",p1->var);
p1=p1->next;
}
printf("\n");
//释放链表内存空间
p1=head;
while(p1){
p2=p1->next;
free(p1);
p1=p2;
}
return 0;
}
由于函数void reversal(struct list* &head)的语法只能用于C++语言,C语言的语法不能识别,要改成C语言的语法的话,可以用指向指针的指针来传递,void reversal(struct list **head),这样就能适应这个算法从而改变head首地址的指向。
C语言代码如下:
#include <stdio.h>
#include <stdlib.h>
struct list{
int var;
struct list *next;
};
void reversal(struct list **head)
{
struct list *p1,*pre,*after,*headNew;
headNew=*head;
p1=headNew;
pre=headNew;
headNew=headNew->next;
while(headNew){
after=headNew->next;
headNew->next=pre;
pre=headNew;
if(after == NULL){
break;
}
headNew=after;
}
p1->next = NULL;
*head=headNew;
}
int main(){
int a[]={1,5,7,8,9,2,4,6,8,9,10,13,16,0};
struct list *head,*p1,*p2;
//创建单向链表
head=(struct list *)malloc(sizeof(struct list));
head->var=a[0];
head->next=NULL;
p1=head;
for(int i=1;i<sizeof(a)/sizeof(int);i++){
head->next=(struct list *)malloc(sizeof(struct list));
head=head->next;
head->var=a[i];
head->next=NULL;
}
head=p1;
//打印单向链表
while(p1){
printf("%2d ",p1->var);
p1=p1->next;
}
printf("\n");
//反转单向链表
reversal(&head);
//打印反转后的单向链表
p1=head;
while(p1){
printf("%2d ",p1->var);
p1=p1->next;
}
printf("\n");
//释放链表内存空间
p1=head;
while(p1){
p2=p1->next;
free(p1);
p1=p2;
}
return 0;
}