反转链表

方法一:递归版本

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;

}





你可能感兴趣的:(反转链表)