题目
思路
用堆栈,反向得到链表的结点。
代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: The head of linked list.
@return: nothing
"""
def reorderList(self, head):
# write your code here
stack = []
node = head
len = 0
while node:
len += 1
stack.append(node)
node = node.next
count = 0
len //= 2
node = head
while stack and count <= len:
count += 1
top = stack[-1]
if node == top:
break
stack.pop(-1)
tmp = node.next
node.next = top
top.next = tmp
node = tmp
if node:
node.next = None
return head