您的位置:首页 > 职场人生

剑指offer面试题16——反转链表

2015-08-06 09:18 363 查看
题目:

输入一个链表,反转链表后,输出链表的所有元素。
(hint:请务必使用链表)

输入:
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000):代表将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):代表链表元素。

输出:
对应每个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。

样例输入:
5
12345
0

样例输出:
54321
NULL

这道题思路是:采用三个指针,因为在反转时中间会出现断裂
注意:若链表为NULL或者若链表为只有一个结点的情况。


#include<iostream>
#include<vector>
usingnamespacestd;

//链表的数据结构
structListNode
{
intval;
ListNode*next;
ListNode(intx):val(x),next(NULL){}
};

//创建一个单链表
ListNode*product(vector<int>&vec,intn)
{
if(n==0)
returnNULL;
ListNode*ptr1=newListNode(vec[0]);
inti=1;
ListNode*ptr2=ptr1;
while(i<n)
{
ptr2->next=newListNode(vec[i]);
ptr2=ptr2->next;
i++;
}
returnptr1;
}

//单链表每个结点的输出
voidcout_node(ListNode*root)
{
if(root==NULL)
return;
ListNode*ptr1=root;
while(ptr1!=NULL)
{
cout<<ptr1->val<<'';
ptr1=ptr1->next;
}
cout<<endl;
return;
}

ListNode*reversed_list(ListNode*root)
{
if(root==NULL)
returnNULL;
if(root->next==NULL)
returnroot;
ListNode*ptr1=root;
ListNode*ptr2=ptr1->next;
ListNode*ptr3=ptr2->next;
ptr1->next=NULL;
while(1)
{
ptr2->next=ptr1;
ptr1=ptr2;
if(ptr3!=NULL)
{
ptr2=ptr3;
ptr3=ptr3->next;
}
else
returnptr2;
}
}
intmain()
{
intary[10]={1,2,3,4,5,6,7,8,9,10};
vector<int>vec(ary,ary+6);
ListNode*root=product(vec,6);
cout_node(root);

ListNode*root2=reversed_list(root);
cout_node(root2);
system("pause");
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: