1,原理
使用p和q两个指针配合工作,使得两个节点间的指向反向,同时用r记录剩下的链表。
p = head;
q = head->next;
head->next = NULL;
![](http://hi.csdn.net/attachment/201110/2/0_1317565566SEbH.gif)
现在进入循环体,这是第一次循环。
r = q->next;
q->next = p;
p = q;
q =r;
第二次循环。
r = q->next
q->next = p;
![](http://hi.csdn.net/attachment/201110/2/0_13175657179L43.gif)
p = q;
q = r
![](http://hi.csdn.net/attachment/201110/2/0_1317565777WHOA.gif)
第三次循环。。。。。
2,代码实现
首先初始化一个空的单链表,然后在单链表中依次插入1-10个元素,然后翻转单链表,然后打印单链表.
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<error.h>
#include<math.h>
#include<pthread.h>
#include<unistd.h>
struct LNode {
int data;
struct LNode *next;
};
typedef struct LNode* LinkList;
/*
void InitList(LinkList L)
{
L = (LinkList)malloc(sizeof(struct LNode));
if(!L) {
printf("malloc L error\n");
return;
}
L->next = NULL;
printf("InitList OK \n");
if(L == NULL) {
printf("InitList L == NULL\n");
}
}
*/
int ListInsert(LinkList L, int i, int e)
{
int j = 0;
static int count = 0;
LinkList p;
LinkList s;
p = L;
if(p == NULL){
printf("p == NULL, count = %d\n",++count);
return -1;
}
while(p && j < i-1)//寻找第i-1个节点
{
p = p->next;
j++;
}
if(!p || j > i-1) { //i<1 或者大于表长
printf("j = %d ,i = %d \n",j,i);
return -1;
}
s = (LinkList)malloc(sizeof(struct LNode));
s->data = e;
s->next = p->next;
//s->next = NULL;
p->next = s;
printf("ListInsert OK \n");
return 1;
}
void PrintList(LinkList L)
{
LinkList p = NULL;
p = L->next;
//printf("%d %d ",p->data,p->next->data);
while(p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
LinkList ReverseList(LinkList L)
{
if(L == NULL || L->next == NULL) {
return L;
}
LinkList p;
LinkList q;
LinkList r;
p = L;
q = L->next;
L->next = NULL;
while(q)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
L = p;
return L;
}
void main(void)
{
int j;
LinkList L;
LinkList Re_L;
LinkList LL;
//InitList(L);
L = (LinkList)malloc(sizeof(struct LNode));
if(!L) {
printf("malloc L error\n");
return;
}
L->next = NULL;
printf("InitList OK \n");
if(L == NULL) {
printf("InitList L == NULL\n");
}
if(L == NULL){
printf("L == NULL\n");
return;
}
for(j=1; j<=10;j++)
ListInsert(L,j,j);
printf("在L的表尾依次插入1-10后:\n");
PrintList(L);
Re_L = ReverseList(L->next);//remove head file .begin with first data element 从首元节点开始
printf("翻转之后的链表:\n");
//PrintList(Re_L);
LL = (LinkList)malloc(sizeof(struct LNode));
LL->next = Re_L; //add a head point 添加一个头节点
PrintList(LL);
}
运行结果:
InitList OK
ListInsert OK
ListInsert OK
ListInsert OK
ListInsert OK
ListInsert OK
ListInsert OK
ListInsert OK
ListInsert OK
ListInsert OK
ListInsert OK
在L中插入1-10后:
1 2 3 4 5 6 7 8 9 10
翻转之后的链表:
10 9 8 7 6 5 4 3 2 1