Jaccorot 日事日毕日清日高

ARTS-010

2020-07-31

一、Algorithm

删除链表中倒数第k个节点


class Node:
    def __init__(self, val):
        self.val = val
        self.next = None


a = Node("1")
b = Node("2")
c = Node("3")
d = Node("4")
e = Node("5")

a.next = b
b.next = c
c.next = d
d.next = e


# t = a
# while t is not None:
#     print(t.val)
#     t = t.next


def del_last_n_node(head: Node, n: int):
    cur = before = head
    count = 1
    before_n = None

    while cur is not None:
        if count > n:
            before_n = before if before_n is None else before_n.next

        count += 1
        cur = cur.next
    if before_n:
        temp = before_n.next.next

        before_n.next.val = None
        before_n.next.next = None

        before_n.next = temp

    elif n == count - 1:
        head = head.next
    while head is not None:
        print(head.val)
        head = head.next

# 快慢节点
# public void getKNode(ListNode head,int k){
#     ListNode slow = head, last = head;
#     while(k>0 && last != null ) {
#         slow = slow.next;
#         k--;
#     }
#     if (slow !=null &&  first != null ){
#         fast=fast.next;
#         slow=slow.next;
#     }
#     slow.next=slow.next.next;
#         return ;
# }

del_last_n_node(a, 5)

二、Review

三、Tip

四、Share

python进阶

  1. python中一切皆对象

  2. type、object和class的关系
  3. python中常见的内置类型

Similar Posts

上一篇 ARTS-009

下一篇 ARTS-011