問題簡述:刪除鏈表中等于給定值val的所有節(jié)點。
有幾種情況需要考慮:
- 最后一個node是None
- 有多個連續(xù)的node與被刪除值相同
- 表頭的node的值=被刪除
- 整個表為None
Python3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @param val, an integer
# @return a ListNode
def removeElements(self, head, val):
# 尋找返回值----head
# 如果鏈表為空
if head == None:
return head
#如果第一個node的值是我們要刪除的值
while head.val == val:
head = head.next # 刪除這個node, 即跳向下一個node
# 如果新的node為空敏沉,跳出循環(huán)
if head == None:
break
# 定義返回值---head
return_head = head
# 如果這個返回值是None,返回None
if return_head == None:
return None
# 當head的下一個節(jié)點不為空
while head.next != None :
# 當head的下一個節(jié)點的值為要刪除的值
while head.next.val == val:
# 將head的指針指向下一個node的指針,即刪除下一個節(jié)點
head.next = head.next.next
# 如果head的指針為空,即已經(jīng)到達鏈表尾部
if head.next == None:
return return_head
#指向下一個節(jié)點
head = head.next
return return_head
既然是刪除贡定,那么就要考慮到垃圾回收的機制:
就python而言 1. 引用計數(shù)機制 2. 標記-清除和分代收集
詳情見Python垃圾回收機制--完美講解!
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
// Write your code here
ListNode return_head = head;
//當head為空時
if( head == null)
{
return return_head;
}
//當頭指針的值等于被刪除的值
while (head.val == val)
{
if (head.next != null )
{
// 刪除這個node,即將這個node的指針指向下一個node的next可都。
head = head.next;
// 記錄頭指針缓待,作為最后的返回參數(shù)。
return_head = head;
}
else{
// 如果下一個的node為none渠牲,那么返回none旋炒。
return null;
}
}
// 當該node的下一個node不為null
while(head.next != null)
{
// 當下一個node的值=被刪除的值
while (head.next.val == val)
{
// 刪除這個node,即將這個node的指針指向下一個node的next
head.next = head.next.next;
// 如果這個node的下一個為null签杈,返回頭指針
if (head.next == null)
{
return return_head;
}
}
head = head.next;
}
return return_head;
}
}
就java而言国葬,Java語言規(guī)范沒有明確地說明JVM使用哪種垃圾回收算法,但是任何一種垃圾回收算法一般要做2件基本的事情:
(1)發(fā)現(xiàn)無用信息對象;
(2)回收被無用對象占用的內(nèi)存空間汇四,使該空間可被程序再次使用。
More info:Java垃圾回收機制