206. Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
反转一个单链表。迭代
# 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
"""
pre=cur=head
if head:
pre=head
cur=head.next
pre.next=None
else:
return None
while cur:
p=cur
cur=cur.next
p.next=pre
pre=p
return pre
92. Reverse Linked List II
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
此题在上题的基础上加了位置要求,只翻转指定区域的链表。由于链表头节点不确定,祭出dummy杀器。此题边界条件处理特别tricky,需要特别注意。
- 由于只翻转指定区域,分析受影响的区域为第m-1个和第n+1个节点
- 找到第m个节点,使用for循环n-m次,使用链表翻转方法
- 处理第m-1个和第n+1个节点
- 返回dummy->next
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if head is None and head.next is None:
return head
dummy=ListNode(0)
dummy.next=head
p=dummy
for i in range(m-1):
p=p.next
curr=p.next
for i in range(n-m):
tmp=curr.next
curr.next=tmp.next
tmp.next=p.next
p.next=tmp
return dummy.next
203. Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
删除链表中等于给定值 val 的所有节点。
遍历所有节点,同时保留每个节点的上一个节点,当遇到节点值是val时,删除该节点。为了方便操作,定义了一个伪头节点。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy=pre=ListNode(0)
pre.next=head
while head:
if head.val==val:
pre.next=head.next
else:
pre=pre.next
head=head.next
return dummy.next