📅  最后修改于: 2023-12-03 14:53:55.280000             🧑  作者: Mango
循环链表是一种链式数据结构,其中最后一个节点指向第一个节点,形成一个“环”。本题要求将初始链表的前 N 个节点拆分为一个新的循环链表,同时保留原始链表的剩余节点。
class Node:
def __init__(self, val):
self.val = val
self.next = None
def split_linked_list(head, n):
"""
:param head: ListNode,初始链表头结点
:param n: int,拆分节点数量
:return: Tuple,新链表头结点与旧链表头结点
"""
if not head:
return None
if n == 1:
new_head = head.next
head.next = None
return new_head, head
count = 1
new_head = head
while count < n and new_head:
new_head = new_head.next
count += 1
if not new_head:
return None
old_tail = new_head
while old_tail.next:
old_tail = old_tail.next
old_head = head
new_head, old_tail.next = old_head, new_head
return new_head, old_head