Description

Reverse a singly linked list.


反转单个链表。


Solution

思路一:采用栈结构,将链表的元素依次压入栈中。然后依次将栈中的元素弹出,后入先出,反转链表。


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 18 16:48:21 2018

@author: Saul
"""
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        poit = head
        linlist = []
        while poit:
            linlist.insert(0, poit.val)
            poit = poit.next

        poit = head
        for i in range(len(linlist)):
            poit.val = linlist[i]
            poit = poit.next
        return head

思路二: 采用“头插法”, 依次拿下链表的节点,在头部插入,从而形成逆向链表。


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 18 16:48:21 2018

@author: Saul
"""
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None    

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head and head.next:
            poit = head
            head = None
            while poit:
                poit2 = poit
                poit = poit.next
                poit2.next = head
                head = poit2
        return head

更多推荐