鍊錶和遞迴

2021-10-19 10:21:23 字數 1515 閱讀 7655

1、leetcode—203

刪除鍊錶元素

不使用虛擬頭結點:

public

class

solution203

if(head==null)

return null;

//中間

listnode prev=head;

while

(prev.next!=null)

else

}return head;

}}

使用虛擬頭結點:(對使用者遮蔽)

public

class

solution203_2

else

}return dummyhead.next;

}}

2、測試leetcode**

把陣列轉成鍊錶:

public

listnode

(int

arr)

}#main

int[

] nums=

;listnode head=

newlistnode

(nums)

;#測試leetcode**

listnode res=

(new

solution203()

).removeelements

(head,6)

;

3、遞迴

將原來的問題,轉化為更小的同一問題。

遞迴函式也是函式

陣列求和:

public

static

intsum

(int

arr,

int l)

#最終呼叫sum

(arr,

0)

4、鍊錶的天然遞迴結構性質

解決leetcode203問題:移除鍊錶中等於給定值val的所有節點

public listnode removeelements

(listnode head,

int val)

//return head.val==val?head.next:head;

}

5、遞迴函式的微觀解讀

遞迴函式的呼叫本質上仍然是函式的呼叫,只不過呼叫的是它本身。

除錯遞迴:用乙個很小的資料集模擬遞迴的呼叫過程。

遞迴代價:函式呼叫+系統棧空間。

6、如何除錯遞迴程式

1)列印輸出

2)跟蹤

7、更多關於鍊錶

近乎所有鍊錶的問題都可以用遞迴解決。

leetcode上關於鍊錶的問題

雙鏈表迴圈鍊錶

陣列鍊錶

4 鍊錶和遞迴

輸入 1 2 6 3 4 5 6,val 6 輸出 1 2 3 4 5 definition for singly linked list.public class listnode class solution if head null listnode prev head while prev....

反轉鍊錶 遞迴和非遞迴實現

include stdafx.h include include struct node void createlink node head,int data void printlink node head void reverselink node head node reverselink n...

C 實現鍊錶遞迴和非遞迴合併

1.使用遞迴和非遞迴實現鍊錶的合併 輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,要求合成後的鍊錶滿足單調不減規則。2.實現 struct listnode 遞迴實現合併兩個排序鍊錶 listnode merge listnode phead1,listnode phead2 else 非遞迴實...