题目:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
思路:
需要记录当前节点,前一个节点,以及后一个节点。首先,初始化一个空节点,空节点是第一个pre节点,head节点是第一个cur节点,head.next是第一个nex节点。将cur的next指针指向pre节点(cur的前一个节点),直到nex节点是空节点。
代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return None
if head.next == None:
return head
H = None
pre = H
cur = head
nex = head.next
while nex != None:
cur.next = pre
pre = cur
cur = nex
nex = nex.next
cur.next = pre
return cur