含有头结点的单链表逆序
最近参加华为机试和中兴笔试都遇到了单链表逆序,在机试过程中采用了投机取巧的办法把结点中的data逆序了一遍,输出结果正确。不过单链表本身并没有发生逆序,防止下次还遇到相同考题,回来还是把单链表逆序给写一下吧!
单链表逆序网上也有一些算法,当然用递归的方法好像更加简单,七叶草等会还要研究一下。含有头结点和不含有头结点的单链表逆序是有所差别的,下面是含有头结点的单链表逆序的C++程序代码:
#include “stdafx.h”
#include <iostream>
using namespace std;
struct Node{
int data;
Node * next;
};
void linkReverse(Node *head)
{
Node *t1,*t2,*t3;
t1=head->next;
t2=t1->next;
t1->next=NULL;
while(t2!=NULL)
{
t3=t2->next;
t2->next=t1;
t1=t2;
t2=t3;
}
head->next=t1;
}
使用Windows7操作系统,32位系统,编译器是Visual Studio 2010,下面是测试程序,:
int _tmain(int argc, _TCHAR* argv[])
{
Node *head=new Node;
Node *p1=new Node;
p1->data=2;
head->next=p1;
Node *p2=new Node;
p2->data=3;
p1->next=p2;
Node *p3=new Node;
p3->data=4;
p2->next=p3;
p3->next=NULL;
Node *temp=head;
linkReverse(head);
temp=head->next;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
return 0;
}
测试程序里面动态分配的结点内存没有删除;在逆序的时候没有考虑空链表的情况。这些都是该单链表逆序程序需要改进的地方,为了省事,这里就没有全部写出来。
by 增高药有用吗 On 九月 26, 2011 at 1:43 上午
对于C++懵懂啊 。