解法一:(头插法)在遍历链表时,将当前节点的 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; // 错误做法