##題目描述 輸入一個鏈表,反轉鏈表后,輸出新鏈表的表頭,
思路
原地反轉鏈表指標,
時間復雜度O(n),空間復雜度O(1),
代碼
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) return null;
ListNode pre = null;
ListNode curr = head;
ListNode next = head.next;
while(next != null) {
curr.next = pre;
pre = curr;
curr = next;
next = next.next;
}
curr.next = pre;
return curr;
}
}
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) return null;
ListNode pre = null;
ListNode p = null;
while(head != null) {
p = head;
head = head.next;
p.next = pre;
pre = p;
}
return p;
}
}
筆記
當while回圈開始時的初設如編碼所示時,根據while回圈中使用了next.next,回圈條件必須判斷next的存在,不然會指標出錯,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/86928.html
標籤:其他
上一篇:鏈表中倒數第k個結點
下一篇:合并兩個排序的鏈表
