題目:
Reverse a singly linked list.
分析:
1. 反轉後頭結點的next為null。
2. 需要同時記錄三個節點,分别是目前節點,它的前節點和next節點。
Java代碼實作:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode node = head;
ListNode pre = head.next;
node.next = null;
while(pre!=null)
{
ListNode temp = pre.next;
pre.next = node;
node = pre;
pre = temp;
}
return node;
}
}