C++ 单向链表反转

时间:2022-02-07 08:50:20

单向链表反转,一道常见的面试题,动手实现下。

 #include "stdafx.h"
#include <stdlib.h>
struct Node{
int data;
Node* next;
}; void print1(Node *head)
{
Node *p;
p=head;
if(head!= NULL)
do
{
printf("%d \n", p->data);
p=p->next;
}while(p!=NULL);
} Node* ReverseList(Node* head)
{
if(head==NULL)
return NULL; Node* cur=head;
Node* pre=NULL;
Node* nx=NULL;
while(cur->next!=NULL)
{
nx=cur->next;
cur->next=pre;
pre=cur;
cur=nx;
}
cur->next=pre;
return cur;
}
Node* init( int num) // insert from back
{
if( >= num)
return NULL;
Node* cur, pre;
Node* head = NULL;
int i = ; cur = head;
Node* new1 = (Node*)malloc(sizeof(Node));
new1->data = ;
head = cur = new1;
for(i = ; i < num; i++)
{
Node* new1=(Node*)malloc(sizeof(Node));
new1->data = i + ;
cur->next = new1;
cur = new1;
}
cur->next = NULL;
return head;
}
int _tmain(int argc, _TCHAR* argv[])
{
Node* list =NULL;
list=init();
print1(list);
Node* newlist=ReverseList(list);
print1(newlist);
getchar();
return ;
}

原理就是把cur节点的next节点保存,把next指向pre节点,把之前保存的next节点赋给cur,不断循环直到next节点为NULL。注意下,退出循环后要把cur节点next指向pre节点。把cur节点返回,大功告成。

如果不用返回值,而是把head=cur;这样可以吗?

可尝试下,那么你会看到打印结果为1。这是因为函数按指针传递,传递的是地址,虽然在reverse函数中head已是一个反转的链表,但在main函数中list仍然指向原来head的地址。换句话说,在反转链表整个过程中地址是不变的,list还是指向data 1的节点。