206. reversal list
- Reverse a singly linked list.
Example:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
Ideas: double pointer iteration
- Apply two pointers and pre cur, cur pointer to the pre, while the two pointers will move forward together.
- When the iteration is complete, cur = None, this time is the pre list head.
Code:
class Solution(object):
def reverseList(self, head):
pre = None
cur = head
# 遍历链表
while cur:
# cur.next, pre, cur = pre, cur, cur.next
# 记录当前节点的下一个节点
tmp = cur.next
# 然后将当前节点指向pre
cur.next = pre
# pre和cur节点都前进一位
pre = cur
cur = tmp
return pre