Method 1: uses self as a dummy node for swapping
def reverseList(self, head):
pre, pre.next, tail = self, head, head
while tail and tail.next:
pre.next, pre.next.next, tail.next = \
tail.next, pre.next, tail.next.next
return self.next
Method 2: swapping using two variable, pre and cur
def reverseList(self, head):
pre, cur = None, head
while cur:
cur.next, pre, cur = pre, cur, cur.next
return pre
Method 3: Recursive method by storing previous node in the function argument.
def reverseList(self, head, pre = None):
if not head: return pre
cur, head.next = head.next, pre
return self.reverseList(cur, head)

这篇博客详细解析了如何反转单链表,包括三种不同的方法:使用自身作为哑节点交换、通过两个变量pre和cur交换,以及递归方法通过函数参数存储前一个节点。
5457

被折叠的 条评论
为什么被折叠?



