方法1:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int ElemType;
typedef struct Node *List;
typedef struct Node *Position;
typedef struct Node Node;
struct Node
{
ElemType Element;
List next;
};
int length_List(List L) //L带头结点
{
int len;
Position temp;
temp=L;
while(temp->next!=NULL)
{
temp=temp->next;
len++;
}
return len;
}
List ReverseList(List L) //反转单链表函数,L带头结点
{
if(L->next->next==NULL||L->next==NULL) //空链表或者只有一个结点
return L;
List Result ,temp; //使用这两个结构体变量,起保护L作用
int len ,i;
Result=(List)malloc(sizeof(Node));
Result->next=NULL;
len=length_List(L);
for(i=0;i<len;i++)
{
temp=(List)malloc(sizeof(Node));
temp->Element=L->next->Element; //临时链表结点,用来存放L链表中的元素
temp->next=Result->next;
Result->next=temp;
L=L->next;
}
return Result;
}
方法2:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int ElemType;
typedef struct Node *List;
typedef struct Node *Position;
typedef struct Node Node;
struct Node
{
ElemType Element;
List next;
};
List ReverseList(List L1) //反转单链表函数,L1带头结点
{
if(L1->next==NULL||L1->next->next==NULL)
return L1;
Position PreviousPos ,CurrentPos ,NextPos;
List L;
L=L1->next; //L无头结点,为处理方便
PreviousPos=NULL;
CurrentPos=L;
NextPos=L->next;
while(NextPos!=NULL)
{
CurrentPos->next=PreviousPos;
PreviousPos=CurrentPos;
CurrentPos=NextPos;
NextPos=NextPos->next;
}
CurrentPos->next=PreviousPos;
return CurrentPos;
}