网上有许多代码 看了一下发现他们的好多反转后都缺失了头结点.
所以自己又写了一个.
//
#include "stdafx.h"
#include "iostream"
using namespace std;
struct ListNode
{
ListNode* next;
int data;
ListNode()
{
next=NULL;
data=0;
}
};
ListNode *ReverseList(ListNode *&list)
{
ListNode *head = list, *last = NULL;
list = list->next;
while (list){
head->next = last;
last = head;
head = list;
list = list->next;
}
head->next = last;
return head;
}
//创建链表添加结点;
void CreateNode(ListNode*&head, int data)
{
ListNode *fist = head;
while (head != NULL)
{
if (head->next == NULL)
{
ListNode *tem = new ListNode();
tem->data = data;
head->next = tem;
break;
}
head = head->next;
}
head = fist;
}
int main(int argc, char* argv[])
{
ListNode *head=new ListNode();
CreateNode(head,1);
CreateNode(head,2);
CreateNode(head,3);
CreateNode(head,4);
CreateNode(head,5);
CreateNode(head,6);
CreateNode(head,7);
ListNode *tem=head;
while (head!=NULL)
{
cout<<head->data<<endl;
head=head->next;
}
ListNode* re=ReverseList(tem);
cout<<"反转链表:"<<endl;
while (re!=NULL)
{
cout<<re->data<<endl;
re=re->next;
}
getchar();
return 0;
}