1. 合并两个有序链表
leetcode 21:https://leetcode-cn.com/problems/merge-two-sorted-lists/
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
代码:
# 定义一个Node类
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
dummy = pre = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
pre.next = l1
l1 = l1.next
else:
pre.next = l2
l2 = l2.next
pre = pre.next
pre.next = l1 or l2
return dummy.next
执行结果:
2. 删除链表的倒数第N个节点
leetcode 19:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
代码:
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if head == None:
return None
first = head
second = head
for i in range(n):
first = first.next
if first == None:
return second.next
while first.next != None:
first = first.next
second = second.next
if(n == 1):
second.next = None
else:
second.next = second.next.next
return head
执行结果:
3. 旋转链表
leetcode 61:https://leetcode-cn.com/problems/rotate-list/
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
思路:
- 求出链表的长度 len
- k = k % len 取余就是我们要右移的距离。
- 找到倒数第 k 个位置。可以使用双指针法。
- 记录慢指针的 next 节点,这就是最后要返回的节点。
代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
# 求出链表的长度
if (head == None or k == 0):
return head
first = head
len = 0
while first != None:
first = first.next
len += 1
k = k % len
if k == 0:
return head
first = head
second = head
while k > 0:
k -= 1
first = first.next
while first.next != None:
first = first.next
second = second.next
res = second.next
second.next = None
first.next = head
return res
执行结果: