链表

2、两数相加

采用递归的思想,当某个链表当前节点存在下一个节点或进位符为1时,往下递归。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode], carryflag = 0) -> Optional[ListNode]:
n1, n2 = l1.val if l1 else 0, l2.val if l2 else 0
s = n1 + n2 + carryflag
val, carry_flag = s % 10, 1 if s > 9 else 0
next1, next2 = l1.next if l1 else None, l2.next if l2 else None
if next1 or next2 or carry_flag:
return ListNode(val, self.addTwoNumbers(next1, next2, carry_flag))
else:
return ListNode(val)

19、删除链表的倒数第N个结点

采用双指针的思想,左右指针都为指向头节点,首先右指针向后遍历n个结点,最后让左右一起向后遍历直至右指针指向的为最后一个结点,这时候左指针指向的就是倒数第n个结点的前一个结点,就可以进行删除的操作了。

但是有一个特殊情况,如果删除的是头结点,上述不成立,所以要单独进行一个if判断,如果右指针向后遍历n个结点后为空,那么删除的就是头结点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
right = head
left = head
for i in range(n):
right = right.next
if right == None: # 如果要删除的是头结点
left = left.next
return left
while right.next != None:
left = left.next
right = right.next
left.next = left.next.next
return head

24、亮亮交换链表中的结点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head == None:
return head
temp = ListNode(0, head)
first = temp
second = temp.next

while second and second.next:
first.next = second.next
second.next = second.next.next
first.next.next = second

first = second
second = second.next
return temp.next

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!