一、獲取單鏈表的節點的個數
public static int getLength(HeroNode head) {
//空鏈表
if(head.next == null) {
return 0;
}
int length = 0;
//定義一個輔助的變量
HeroNode cur = head.next;
while (cur != null) {
length ++;
cur = cur.next;
}
return length;
}
二、查找單鏈表中倒數第K個節點
思路:
1.編寫一個方法,接收head節點,同時接收一個index
2.index表示倒數第index個節點
3.先把鏈表從頭到尾遍歷,得到鏈表的總長度(getLength)
4.得到size後,從鏈表的第一個開始遍歷(size-index)個,就可以得到
public static HeroNode findLastIndexNode(HeroNode head, int index) {
if(head.next == null) {
return null;
}
//第一次遍歷得到鏈表長度
int size = getLength(head);
//第二次遍歷size-index位置,就是我們倒數的第K個節點
if(index <= 0 || index > size) {
return null;
}
//定義輔助的變量,for循環定位到倒數的index
HeroNode cur = head.next;
for (int i = 0; i < size - index; i++) {
cur = cur.next;
}
return cur;
}
三、將單鏈表反轉
public static void reverseList(HeroNode head) {
//如果當前鏈表爲空,或者只有一個節點,無需反轉,直接返回
if(head.next == null || head.next.next == null) {
return;
}
//定義一個輔助的變量,幫助我們遍歷原來的鏈表
HeroNode cur = head.next;
//指向當前節點的下一個節點
HeroNode next = null;
HeroNode reverseHead = new HeroNode(0, "", "");
while (cur != null) {
//暫時保存當前節點的下一個節點
next = cur.next;
//將cur的下一個節點指向新的鏈表的最前端
cur.next = reverseHead.next;
//將cur連接到新的鏈表上
reverseHead.next = cur;
//讓cur後移
cur = next;
}
//將head.next指向reverseHead.next,實現單鏈表的反轉
head.next = reverseHead.next;
}
四、逆序打印鏈表,利用棧
public static void reversePrint(HeroNode head) {
if(head.next == null) {
return;
}
Stack<HeroNode> stack = new Stack<>();
HeroNode cur = head.next;
//將鏈表的所有節點壓入棧
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
while (stack.size() > 0) {
System.out.println(stack.pop());
}
}