一.獲得單鏈表節點個數
簡單
public static int showHeadNumbers(HeroNode headNode) {
HeroNode tmp = HeadNode;
int count = 0;
while (tmp.next != null) {
count++;
tmp = tmp.next;
}
return count;
}
二.獲得單鏈表倒數第n個節點
1.獲得倒數第index個節點信息 , 倒數第一個就是正數的(總數-1).next個 倒數第二個就是正數的(總數-2).next個
所以使用for循環 到第 (總數-1) 個,然後取 (總數-1).next 即可
public HeroNode getReciprocalHead(HeroNode headNode, int index) {
if (headNode.next == null) {
return null;
}
int allNumbers = showHeadNumbers(headNode);
if (index > allNumbers || index < 0) {
return null;
}
HeroNode tmp = headNode;
for (int i = 0; i <=allNumbers - index; i++) {
tmp=tmp.next;
}
return tmp; }}
三.反轉鏈表
1.用來存倒序的新鏈表 2.保存指針位置,也是取出的哪一個節點 3.保存取出的那一串鏈表,以便 指針後移
注意鏈表是一串 tmp.next = newHeroNode.next; newHeroNode.next =tmp; 將一個節點拆開到新的鏈表
public HeroNode getReverseHeroNode(HeroNode headNode) {
HeroNode newHeroNode = new HeroNode(0, "", ""); //用來存倒序的新鏈表
HeroNode tmp = headNode.next; // 保存指針位置,也是取出的哪一個節點
HeroNode removedTmp; //保存取出的那一串鏈表
while (tmp!=null){
removedTmp=tmp.next; //先將後面的保存起來
tmp.next = newHeroNode.next; //把取出的節點的下一位指向 新鏈表的下一位
newHeroNode.next =tmp; ////把新鏈表的下一位 指向取出的節點
tmp=removedTmp;
}
headNode.next=newHeroNode.next;
return headNode; }
四.倒序打印鏈表(利用棧)
* 在不改變鏈表結構下,將鏈表倒序打印 循環鏈表放入棧,利用棧先進先出原理打印
public void showReverseHeroNode(HeroNode heroNode) {
if (heroNode.next == null) {
System.out.println("鏈表爲空!");
return;
}
Stack<HeroNode> stackheroNode = new Stack<HeroNode>();
HeroNode cur = heroNode.next;
while (cur != null) {
stackheroNode.push(cur);
cur = cur.next;
}
while (stackheroNode.size() > 0) {
System.out.println(stackheroNode.pop()); }}