Reverse a singly linked list
Description
Given a linked list, remove the n-th node from the end of list and return its head.
Example1:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Tags: LinkedList
解讀題意
翻轉單向鏈表
思路1
1. 保存head下一節點
2. 將head所指向的下一節點改爲prev
3. prev替換爲head
4. 將第一步保存的下一節點替換爲head,用於下次循環
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
// fix head
head = prev;
return head;
}
}
leetCode彙總:https://blog.csdn.net/qingtian_1993/article/details/80588941
項目源碼,歡迎star:https://github.com/mcrwayfun/java-leet-code