206. Reverse Linked List
# Easy

Solution
temp records next node, head is current node, preNode is the pre-node of head. Don't forget to initialise preNode = NULL, return new head.
temp 记录下一个节点,head表示当前节点,preNode表示head的母节点。必须初始化preNode=NULL,并且最后返回新的头节点(即最后一个节点)。
record next node temporally
let head.next point to preNode
move to next node
暂时记录下一个节点
让head.next指向前一个节点
指针后移一位
Python syntax
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode pre = null;
ListNode curr = new ListNode();
curr = head;
while(curr != null) {
ListNode nextTemp = curr.next;
curr.next = pre;
pre = curr;
curr = nextTemp;
}
return pre;
}
}# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
while head != None:
temp = head.next
head.next = pre
pre = head
head = temp
return preLast updated
Was this helpful?