引言
将一个没有空结点作为头的单链表实现反转。其实质就是将结点的指针域指向反转。定义指向当前结点的指针,指向前一个结点的指针,指向当前结点的后一个结点的指针,这个过程中包含只有一个结点的单链表,那么反转之后还是它本身,只有两个结点的单链表,反转之后由第一个结点的指针指向第二个结点,第二个结点的指针域指向为空,变为第二个结点的指针指向第一个结点,第一个结点的指针域为空。当结点数大于二,便就是一系列结点指针指向的反转,最后记得将反转后的单链表的尾结点的指针指向空。
示例
下面是在vs2010上实现的单链表反序。
// reverseList.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
/***********************
功能:实现无头单链表的反序
包含的功能函数:
struct Node* createList(int n,int data) 创建n的结点的单链表,链表采用data++的形式增减每一个结点的值
struct Node* reverseList(struct Node **pList) 将但联编反序,大致的形式类似:1-》2-》3 反序后3-》2-》1
void printList(struct Node *pList) 输出;链表pList的结点元素
**********************/
struct Node
{
int num;
struct Node *next;
};
struct Node* createList(int n,int data)
{
struct Node *ph = NULL;
struct Node *pnow = NULL;
struct Node *pLast = NULL;
while (n >= 0)
{
struct Node *pNode = new struct Node;
pNode->next = NULL;
pNode->num = data++;
if(ph == NULL)
{
ph = pNode;
}
pnow = pNode;
if(pLast != NULL)
{
pLast->next = pnow;
}
pLast = pnow;
--n;
}
return ph;
}
struct Node* reverseList(struct Node **pList)
{
struct Node *pre = *pList;//指向前一个结点
struct Node *pCur = NULL;//指向当前结点
struct Node *pNext = NULL;//指向当前结点的下一个结点
if(pre->next != NULL)
{
pCur = pre->next;
if(pCur->next != NULL)//结点数最少为3个
{
pNext = pCur->next;
pre->next = NULL;
while(pCur)
{
pCur->next = pre;
if(pNext)
{
pre = pCur;
pCur = pNext;
pNext = pNext->next;
}
else
{
break;
}
}
return pCur;
}
else//只有两个结点
{
pCur->next = pre;
pre->next = NULL;
return pCur;
}
}
else//只有一个结点
{
return pre;
}
}
void printList(struct Node *pList)
{
struct Node *ph = pList;
while(ph != NULL)//注意这里是结点不为空ph != NULL,不是结点的指针指向不为空ph->next != NULL
{
cout<<ph->num<<"\t";
ph = ph->next;
}
cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
struct Node *pList = createList(4,1);
printList(pList);
cout<<"================="<<endl;
struct Node * ph = reverseList(&pList);
printList(ph);
system("pause");
return 0;
}
程序的运行效果如下:
仅以记录。