單鏈表的base 高頻面試題

2021-10-06 23:40:49 字數 3655 閱讀 8504

鍊錶是有序的列表,但是它在記憶體中是儲存如下

新增:
public

class

singlelinkedlist

}/**

*定義singlelinkedlist單鏈表

*/class

singlelinkedlistd

temp = temp.next;

} temp.next = heronode;

}/**

* 顯示鍊錶

* 先判斷為空,遍歷後temp後移,否則就是死迴圈

*/public

void

list()

heronode temp = head.next;

while

(true

) system.out.

println

(temp)

; temp = temp.next;}}

}/**

*no:編號 name:名字 nickname:暱稱

*/class

heronode

@override

public string tostring()

';}}

排序新增:
/**

*根據排名到指定位置,如果有這個排名,則增加失敗

*/public

void

addlist

(heronode heronode)

//位置找到,插入到temp的後面

if(temp.next.no > heronode.no)

else

if(temp.next.no == heronode.no)

temp = temp.next;

}//判斷result的值

if(result)

else

}

修改:
/**

* 根據newheronode的no來修改

* @param newheronode

*/public

void

update

(heronode newheronode)

heronode temp = head.next;

boolean result =

false

;while

(true)if

(temp.no == newheronode.no)

temp = temp.next;}if

(result)

else

}

刪除:
/**

*刪除* result 標誌是否找到

* @param no

*/public

void

delete

(int no)

if(temp.next.no == no)

temp = temp.next;}if

(result)

else

}

1、有效節點個數:
public

static

intlength

(heronode head)

int length =0;

heronode temp = head.next;

while

(temp != null)

return length;

}

/**

*查詢鍊錶倒數第 k 個節點

* 思路:遍歷到size - index

* @param head 從頭部開始遍歷

* @param index 倒數第index個節點

*/public

static heronode findlastnode

(heronode head,

int index)

int size =

length

(head);if

(index <=

0|| index > size)

heronode temp = head.next;

for(

int i =

0; i

)return temp;

}

/**

* 定義乙個新的節點,然後從頭開始遍歷,每遍歷乙個,取出放入新的鍊錶最前端

* head.next = newhero.next; 實現單鏈表的反轉

* next 指向當前節點【temp】的下乙個節點

* next = temp.next; 暫時保管當前指向的下乙個節點

* temp.next = newhero.next; 將下乙個節點指向當前鍊錶的最前端

* newhero.next = temp; 將temp連線到新的鍊錶上

* temp = next; temp後移

* @param head

*/public

static

void

reversetlist

(heronode head)

heronode newhero =

newheronode(0

,"",""

);heronode temp = head.next;

heronode next = null;

while

(temp != null)

head.next = newhero.next;

}

方式二:可以將各個節點壓入棧中,先進後出

/**

* 利用棧的先進後出

* @param head

*/public

static

void

reverseprint

(heronode head)

stack

stack =

newstack

<

>()

; heronode temp = head.next;

while

(temp != null)

while

(stack.

size()

>0)

}

5、查詢指定元素
/**

* 查詢指定元素

* @param head

* @param no

* @return

*/public

static heronode find

(heronode head,

int no)

else

size--;}

return temp;

}

單鏈表的面試題

自定義標頭檔案部分 void deletenottail pnode pos 刪除乙個無頭單鏈表的非尾節點 void insertnothead pnode phead,pnode pos,datatype data 在無頭單鏈表的乙個非頭節點前插入乙個節點 void josephcircle pn...

面試題 單鏈表反轉

問題 定義乙個函式,輸入乙個鍊錶的頭結點,反轉該鍊錶並輸出反轉後鍊錶的頭結點。一 非遞迴演算法 假設有鍊錶a b c d e f g。在反轉鍊錶過程中的某一階段,其鍊錶指標指向為 a b c d e f g。也就是說在結點d之前的所有結點都已經反轉,而結點d後面的結點e開始的所有結點都沒有反轉。這樣...

單鏈表 (面試題)

關於單鏈表的基本操作,之前已經總結過了,那些掌握之後算是了解了單鏈表是什麼?不過現在面試的題中,肯定不會只讓你回答單鏈表的基礎操作,總是會改變一些東西,或是擴充套件一下。下面就是一些關於單鏈表的擴充套件內容 include include include pragma warning disable...