目錄
LeetCode-206題
LeetCode-206題
給定一個單鏈表的頭節點,請反轉鏈表,并返回反轉后的鏈表
class Solution {public ListNode reverseList(ListNode head) {// checkif (head == null || head.next == null)return head;// 雙指針ListNode p1 = head;ListNode p2 = head.next;// 一直到p2指向nullwhile (p2 != null) {ListNode curr = p1;p1 = p2;if (curr == head) {curr.next = null;}// 定義一個臨時變量存放此時p2的下一個節點ListNode tmp = p2.next;p2.next = curr;p2 = tmp;}return p1;}private static class ListNode {int val;ListNode next;public ListNode() {}public ListNode(int val) {this.val = val;}public ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
}