目錄
- 題目描述:
- 示例 1:
- 示例 2:
- 代碼實現:
題目描述:
給定單鏈表的頭節點 head ,請反轉鏈表,并返回反轉后的鏈表的頭節點。
示例 1:
輸入:head = [1,2,3,4,5]
輸出:[5,4,3,2,1]
示例 2:
輸入:head = [1,2]
輸出:[2,1]
代碼實現:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode reverseList(ListNode head) {ListNode cur = new ListNode();// 遍歷節點cur = head;// 指向頭節點ListNode pre = null;// 反轉之后的尾節點ListNode tmp = new ListNode();// 臨時節點:存儲當前遍歷的后繼while (cur != null) {tmp = cur.next;// 記錄當前的后繼cur.next = pre;// 當前指向前驅pre = cur;// 前驅指針指向當前cur = tmp;// 當前指向臨時節點}return pre;// 返回最后遍歷的節點:即反轉之后的頭節點}
}