List 206. The reverse list

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

  1. Apply two pointers and pre cur, cur pointer to the pre, while the two pointers will move forward together.
  2. When the iteration is complete, cur = None, this time is the pre list head.
    Here Insert Picture Description

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	
Published 29 original articles · won praise 2 · Views 1770

Guess you like

Origin blog.csdn.net/yhhuang17/article/details/104816568