解法一:(頭插法)在遍歷鏈表時,將當前節點的 next 指針改為指向前一個節點。
/*** 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 prev=null;ListNode curr=head;while(curr != null){// 頭插法ListNode temp = curr.next;curr.next = prev;prev = curr;curr = temp;}return prev;}
}
注意:
- 這里的
ListNode
是類,而不是C++中的指針,不能對listNode.next
進行賦值。 - 申請一個新的
ListNode
要new ListNode()
- 以下為錯誤做法,記住
ListNode
是類,而不是C++中的指針
ListNode prev = new ListNode(); // 錯誤做法
prev.next = null; // 錯誤做法
ListNode curr = head;
while(curr != null){// 頭插法ListNode temp = curr.next;curr.next = prev.next; // 錯誤做法