面试题-链表反转c实现
// ListReverse.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <malloc.h>
#include <iostream>
using namespace std;
typedef struct List
{
struct List *next;
int data;
}*ListPtr;
void PrintList(ListPtr list)
{
while(list!=NULL)
{
cout<<list->data<<"->";
list = list->next;
}
cout<<endl;
}
ListPtr ReverseList(ListPtr list)
{
if((list == NULL) || (list->next ==NULL))
{
return list;
}
ListPtr head = list;
ListPtr headnext = head->next;
ListPtr headnextnext = headnext->next;
head->next = NULL;
while(headnextnext != NULL)
{
headnext->next = head;
head = headnext;
headnext = headnextnext;
headnextnext = headnextnext->next;
}
headnext->next = head;
return headnext;
}
int _tmain(int argc, _TCHAR* argv[])
{
ListPtr head = (ListPtr)malloc(sizeof(List));
ListPtr headtemp = head;
int i=10;
while(i--)
{
headtemp->data = i;
headtemp = headtemp->next = (ListPtr)malloc(sizeof(List));
}
headtemp->data = i;
headtemp->next = NULL;
PrintList(head);
PrintList(ReverseList(head));
return 0;
}
作者:
HarlanC
博客地址:
http://www.cnblogs.com/harlanc/
个人博客:
http://www.harlancn.me/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出,
原文链接