今天在不同地方看到了链表翻转的题目,就自己亲手写了两种方法,一般方法和递归方法。(程序里边还有一些构建链表,遍历链表,销毁链表以及测试的函数)
/************************************************************************/
/* 链表翻转 wzq 2014-01-20 */
/************************************************************************/
#include <iostream>
using namespace std;
//定义链表节点结构
struct node{
int data;
struct node * next;
};
typedef struct node node ,*nodeP;
//函数声明
nodeP createList(int *data,int len);//构造链表
void listReversal(nodeP &list);//翻转链表
void listReversal2(nodeP &rList,nodeP list);//翻转链表 递归方法
void traversList(nodeP list);//遍历链表
void destoryList(nodeP list);//销毁链表
int main()
{
int a[] = {1,2,3,4,5,6,7,8};
nodeP list = createList(a,sizeof(a)/sizeof(a[0]));
listReversal(list);
traversList(list);
nodeP newList = NULL;
listReversal2(newList,list);
traversList(newList);
destoryList(newList);
system("pause");
return 0;
}//end main
//构造链表
nodeP createList(int *data,int len)
{
if(NULL == data || 0 == len) exit(1);
nodeP head = NULL;
nodeP p = NULL;
for (int i=0; i<len; i++)
{
nodeP newNode = new node;
newNode->data = data[i];
newNode->next = NULL;
if (NULL == head)
{
p = head = newNode;
}
else
{
p->next = newNode;
p = p->next;
}
}
return head;
}//end createList
//翻转链表
void listReversal(nodeP &list)
{
nodeP head = NULL;
nodeP temp = NULL;
while(NULL != list)
{
temp = list;
list = list->next;
temp->next = head;
head = temp;
}
list = head;
}//end listReversal
//翻转链表 递归方法
void listReversal2(nodeP &rList,nodeP list)
{
nodeP p = list;
list = list->next;
p->next = rList;
rList = p;
if (list)
listReversal2(rList,list);
}//end listReversal2
//遍历链表
void traversList(nodeP list)
{
while(NULL != list)
{
cout << list->data << " ";
list = list->next;
}
cout << endl;
}//end traversList
//销毁链表
void destoryList(nodeP list)
{
nodeP temp = NULL;
while (list)
{
temp = list;
list = list->next;
delete temp;
}
}//end destoryList