📅  最后修改于: 2023-12-03 14:54:57.217000             🧑  作者: Mango
在单向链表中,每个节点只有指向下一个节点的引用,从而形成一个链式结构。交换单向链表的第一个和最后一个节点需要遍历整个链表,找到链表的头节点和尾节点,然后交换它们。
交换单向链表的第一个和最后一个节点需要遍历整个链表,找到链表的头节点和尾节点,然后交换它们。具体实现思路如下:
def swap_first_and_last(head):
if not head or not head.next:
return head
cur = head
length = 1
while cur.next:
cur = cur.next
length += 1
last = cur
cur = head
for _ in range(length-2):
cur = cur.next
first = cur.next
cur.next = None
last.next = head
first.next = None
return last
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
def print_list(head):
cur = head
while cur is not None:
print(cur.val, end=' ')
cur = cur.next
print()
def main():
head = Node(1, Node(2, Node(3, Node(4, Node(5)))))
print_list(head)
head = swap_first_and_last(head)
print_list(head)
if __name__ == '__main__':
main()
输入:
1 -> 2 -> 3 -> 4 -> 5
输出:
5 -> 2 -> 3 -> 4 -> 1