1.求單鏈表中有效結點的個數(新浪)
//獲取單鏈表結點的個數
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;
}
2.求單鏈表中倒數第k個結點(新浪)
//查找單鏈表倒數第k個結點
//1.獲取單鏈表長度length
//2.遍歷length-k次即可
public static HeroNode findLastIndexNode(HeroNode head,int index){
if (head.next == null){
return null;
}
int length = getLength(head);
if (index < 0 || index > length){
return null;
}
HeroNode cur = head.next;
for (int i = 0; i < length-index; i++) {
cur = cur.next;
}
return cur;
}
3.單鏈表的反轉(騰訊)
//單鏈表的反轉
public void reverseList(HeroNode head){
//如果爲空,或者只有1個結點時,不需要反轉
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.next = reverseHead.next;
reverseHead.next = cur;
cur = next;
}
//將head的next指向reverseHead的next,實現反轉
head.next = reverseHead.next;
}
4.從尾到頭打印單鏈表(百度)
//從尾到頭打印單鏈表
//1.先進後出=>棧
public 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;
}
//棧內大於0
while(stack.size() > 0){
System.out.println(stack.pop());
}
}
5.合併兩個有序單鏈表
//合併兩個有序的單鏈表
//1.判斷兩個單鏈表哪個小,小的加入
//2.添加兩個單鏈表最後剩下的
public static HeroNode mergeLinkedList(HeroNode head1,HeroNode head2){
//創建新的頭結點
HeroNode newHead = new HeroNode(0,"","");
//尾指針
HeroNode rear = newHead;
if (head1.next == null){
newHead.next = head2.next;
return newHead;
}
if (head2.next == null){
newHead.next = head1.next;
return newHead;
}
//兩個鏈表的工作指針
HeroNode cur1 = head1.next;
HeroNode next1 = null;
HeroNode cur2 = head2.next;
HeroNode next2 = null;
//當鏈表1和2都不到尾部時
while(cur1 != null && cur2 != null){
//判斷大小
if (cur1.no < cur2.no){
//後指針
next1 = cur1.next;
//插入位置,尾指針後移
cur1.next = rear.next;
rear.next = cur1;
rear = cur1;
//工作指針迴歸
cur1 = next1;
}
else{
//後指針
next2 = cur2.next;
//插入位置,尾指針後移
cur2.next = rear.next;
rear.next = cur2;
rear = cur2;
//工作指針迴歸
cur2 = next2;
}
}
//添加剩餘的鏈表
while(cur1 != null){
next1 = cur1.next;
cur1.next = rear.next;
rear.next = cur1;
cur1 = next1;
}
while(cur2 != null){
next2 = cur2.next;
cur2.next = rear.next;
rear.next = cur2;
cur2 = next2;
}
return newHead;
}