链表的反转,采用头插法
链表程序如下:
#pragma once #include "stdlib.h" #include<iostream> using namespace std; typedef struct sNode {
int data;
sNode *next;
}Node; void InitList(); void ReverseList();
#include "ReverseList.h" int data[] = {1,2,3,4,5,6,7,8,9}; Node* head = NULL; void InsertList() {
if (!head)return;
for (int i = 0; i < sizeof(data)/sizeof(int);i++)
{
Node *temp = (Node*)malloc(sizeof(Node));
temp->data = data[i];
temp->next = head->next;
head->next = temp;
}
} void PrintList() {
if (!head)return;
Node *temp = head->next;
cout<<"head->";
while(temp != NULL)
{
cout<<temp->data;
cout<<"->";
temp = temp->next;
}
cout<<endl;
} void InitList() {
head = (Node*)malloc(sizeof(Node));
if (NULL == head)return;
head->data = 0;
head->next = NULL;
InsertList();
PrintList();
} void ReverseList() {
if (!head)return;
Node *temp = head->next;
Node *next;
while (temp)
{
next = head->next;
if (NULL != temp->next)
{
head->next = temp->next;
temp->next = temp->next->next;
head->next->next = next;
}
else
break;
}
PrintList();
}
参考:http://www.cnblogs.com/pianoid/archive/2011/05/03/reverse-a-singly-linked-list.html