/*
* reverse_list.cpp
*
* Created on: 2012-5-22
* Author: ict
*/
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
//定义结构体
typedef struct NODE
{
int data;
struct NODE *next;
}*PNode, NODE;
/*
* 核心函数
* 输入:链表的头指针
* 输出:链表置反后的尾指针,其实就是头指针head,但是顺序已经改变,head已经变成了tail
*/
PNode reverse(PNode head)
{
PNode tail;
if (head->next == NULL) //最后一个节点,直接返回
return head;
else //否则递归调用
{
tail = reverse(head->next);
tail->next = head;
head->next = NULL;
return head;
}
}
int main()
{
int n;
int i;
int temp;
PNode head;
PNode tail, q;
tail = NULL;
head = (PNode) malloc(sizeof(NODE));
head->next = NULL;
printf("Please input the number:");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d", &temp);
q = (PNode) malloc(sizeof(NODE));
q->data = temp;
q->next = NULL;
if (tail != NULL)
tail->next = q;
tail = q;
if (i == 0)
{
head->next = q;
}
}
q = head->next;
for (i = 0; i < n; i++)
{
printf("%d ", q->data);
q = q->next;
}
printf("\n");
reverse(head->next);
for (i = 0; i < n; i++)
{
printf("%d ", tail->data);
tail = tail->next;
}
printf("\n");
return 0;
}
最近看自己以前写的博客,加上看过一些面试题,自己写了一个采用递归方法,原地置反链表的程序,代码如下: