反转链表
来源:互联网 发布:腾讯阿里云 编辑:程序博客网 时间:2024/04/29 12:10
方法一:递归版本
- C/C++ code
template
<
typename T
>
ListNode
<
T
>*
reverse_slist_recursive(ListNode
<
T
>*
head)
{
if
(
!
head
||!
(head
->
next))
return
head;
ListNode
<
T
>*
rtn
=
reverse_list(head
->
next);
head
->
next
->
next
=
head;
head
->
next
=
NULL;
return
rtn;
}
方法二:利用循环
- C/C++ code
template
<
typename T
>
ListNode
<
T
>*
reverse_slist_common(ListNode
<
T
>*
head)
{
if
(
!
head
||!
(head
->
next))
return
head;
ListNode
<
T
>
*
prev
=
0
;
while
(head)
{
ListNode
<
T
>
*
temp
=
head;
head
=
head
->
next;
temp
->
next
=
prev;
prev
=
temp;
}
return
prev;
}
方法三:利用辅助栈
- C/C++ code
template
<
typename T
>
ListNode
<
T
>*
reverse_slist_usingstack(ListNode
<
T
>*
head)
{
if
(
!
head
||!
(head
->
next))
return
head;
ListNode
<
T
>
*
prev
=
0
,
*
pcur
=
0
;
stack
<
ListNode
<
T
>*>
sl;
while
(head)
{
sl.push(head);
head
=
head
->
next;
}
head
=
pcur
=
sl.pop();
while
(
!
sl.empty())
{
prev
=
sl.pop();
pcur
->
next
=
prev;
pcur
=
prev;
}
pcur
->
next
=
0
;
return
head;
}
- 链表反转
- 反转链表
- 单向链表反转
- 链表反转:
- 链表的反转
- 链表反转
- 反转单向链表
- 链表反转
- 单向链表反转
- 单向链表反转
- 链表的反转
- 链表反转
- 反转链表
- 链表反转
- 链表反转
- 链表反转
- 链表反转
- 链表的反转
- Windows程序的关闭过程
- Comparison between Apache Axis2 and Apache cxf on stack flow
- VC保存和显示数据库图像(JPG、JPEG)
- CString::Format问题
- 碰撞检测与模型运动
- 反转链表
- effective C++ 条款05 to 条款12
- test
- servlet
- java程序发布之jre篇
- 一个很实用的VC系统托盘例子
- 关于函数指针用于类成员函数
- VC从系统进程中查找并杀掉指定进程
- 【破解利器】编译工具(Compilers) + 编辑工具