A review on basic operation of list reversing.
Base template
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# iteration
def reverseN(head: listNode, n: int) -> listNode:
if head is None or head.next is None:
return head
pre, cur, nxt = None, head, head.next
while n and cur:
cur.next = pre
pre = cur
cur = nxt
if nxt is not None:
nxt = nxt.next
n -= 1
head.next = cur
return pre
|
1
2
3
4
5
6
7
8
9
10
11
|
# recursion
successor = None
def reverseN(head: ListNode, n: int):
global successor
if n == 1:
successor = head.next
return head
last = reverseN(head.next, n-1)
head.next.next = head
head.next = successor
return last
|