206. Reverse Linked List(链表反转)
Reverse a singly linked list.
Subscribe to see which companies asked this question.
利用循环。
注意反转后,原来的头节->next = null
# 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: Optional[ListNode]) -> Optional[ListNode]: pre = None cur = head while cur: c_next = cur.next cur.next = pre pre = cur cur = c_next return pre
递归版
1 public class Solution { 2 public ListNode reverseList(ListNode head) { 3 if(head == null ||head.next == null) return head; 4 ListNode pre = head; 5 head = head.next; 6 ListNode newhead = reverseList(head); 7 pre.next = null; 8 head.next = pre; 9 return newhead; 10 11 } 12 }