将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
num1 =[]
x1 = l1
while x1 != None:
num1.append(x1.val)
x1 = x1.next
num2 = []
x2 = l2
while x2 != None:
num2.append(x2.val)
x2 = x2.next
num = num1 + num2
num = sorted(num)
head = ListNode(0)
pre = head
for i in num:
pre.next = ListNode(i)
pre = pre.next
return head.next
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if head.next is None:
return None
p1 = head
p2 = p1
for _ in range(n):
if p1.next != None:
p1 = p1.next
else:
return head.next
while p1.next != None:
p1 = p1.next
p2 = p2.next
p2.next = p2.next.next
return head
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
p, rev = head, None
while p:
rev, rev.next, p = p, rev, p.next
return rev