在单链表和双链表中删除倒数第K个节点
生活随笔
收集整理的這篇文章主要介紹了
在单链表和双链表中删除倒数第K个节点
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目:分別實(shí)現(xiàn)兩個(gè)函數(shù),一個(gè)可以刪除單鏈表中倒數(shù)第k個(gè)節(jié)點(diǎn),另一個(gè)可以刪除雙鏈表中倒數(shù)第k個(gè)節(jié)點(diǎn)
要求:如果鏈表長(zhǎng)度為N,時(shí)間復(fù)雜度達(dá)到O(N),額外空間復(fù)雜度達(dá)到O(1)
"""單鏈表"""class Node:def __init__(self,value):self.value = valueself.next = Nonedef removeLastKth(head,k):if head == None or k<1:return headcur = headwhile cur!=None:k-=1cur = cur.nextif k == 0:head = head.nextelif k < 0:cur = headwhile k+1!=0:k = k+1cur = cur.nextcur.next = cur.next.nextreturn head """雙鏈表""" class DoubleNode:def __init__(self,val):self.val = valself.next = Noneself.pre = Nonedef removeLastKth(self,k):if head == None or k < 1:return headcur = headwhile cur!=None:k -=1cur = cur.nextif k == 0:head = head.nexthead.pre = Noneelif k < 0:cur = headwhile k!=0:k +=1cur = cur.nextcur.next = cur.next.nextif cur.next!=None:cur.next.pre = curreturn head?
總結(jié)
以上是生活随笔為你收集整理的在单链表和双链表中删除倒数第K个节点的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 矩阵的最小路径和
- 下一篇: 删除链表的中间节点和a/b处的节点