反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
一、思路:利用三个节点互换达到反转链表的目的:
新建节点p,q.原链表头节点head记为h,令p=h ,q=h.next,如下图;
1、翻转节点1、2
h q
1->2->3->4->5
p
(1)令h.next=h.next.next:
h q
1->3->4->5 2->3->4->5
p
(2)令q.next=p:
h
2->1->3->4->5
q p
这样2和1就反转过来了
(3)令p=q,q=h.next,为下次准备:
p h q
2->1->3->4->5
2、翻转2和3
(1)再次令h.next=h.next
p h q
2->1->4->5 3->4->5
(2)q.next=p:
q p h
3->2->1->4->5
这样,3,2,1也反转过来了
(3)复位:
p h q
3->2->1->4->5
3、重复直到h的next=null,这样链表就反转过来了
二、代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode t=head;
ListNode p=head;
if(head==null || head.next==null){
return head;
}
while(head.next!=null){
t=head.next;
head.next=head.next.next;
t.next=p;
p=t;
}
head=p;
return head;
}
/*算法(h=head,t=t,p=p):
h t
① 1->2->3->4->5
p
h t
② 2->1->3->4->5
p
h t
③ 3->2->1->4->5
p
*/
}