题35. 翻转链表
翻转一个链表
样例:给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: n
@return: The new head of reversed linked list.
"""
def reverse(self, head):
# write your code here
# 注意边界
# 定义两个指针,一个指向新链表的头结点,一个指向原结点,用于遍历
# 还有一个辅助指针,记录原结点的后继,以免断链
if head is None:
return
if head.next is None:
return head
new=head
pre=None
while new:
res=new
tmp=new.next
new.next=pre
pre=new
new=tmp
return pre
题96. 链表划分
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
样例:给定链表 1->4->3->2->5->2->null,并且 x=3
返回 1->2->2->4->3->5->null
def partition(self, head, x):
# write your code here
# 借助了两个链表,一个存放小于的数字,另一个存放不小于的数字
if head is None:
return head
minl=ListNode(0)
pre1=minl
maxl=ListNode(0)
pre2=maxl
pre=head
while pre:
if pre.val<x:
pre1.next=pre
pre1=pre1.next
else:
pre2.next=pre
pre2=pre2.next
pre=pre.next
pre2.next=None##注意
pre1.next=maxl.next
return minl.next