1、求单链表中有效节点的个数
思路:
先预设一个计数,然后遍历链表。
public int sum(){
if(this.head.next == null){
return 0;
}
HeroNode temp = this.head;
int count = 0;
while(temp.next != null){
count++;
temp = temp.next;
}
return count;
}
2、查找单链表中倒数第k个节点
思路:
方法1:
1.先求出单链表的有效节点个数n
2.然后开始遍历单链表,遍历次数等于n-k
方法2:
使用Stack栈,先遍历单链表,并将节点一一存入stack中,然后从stack中取数据,取的次数就是k。
这里只写了方法1
public HeroNode reverseIndex(int k) {
if(head.next == null) {
System.out.println("链表为空,无法获取倒数第"+k+"个节点");
return null;
}
int count = this.sum();
if(k>count) {
throw new IndexOutOfBoundsException("下标越界");
}
HeroNode temp = head.next;
for (int i = 0; i < count-k; i++) {
temp = temp.next;
}
return temp;
}
3、单链表的反转
思路:头插法
1.新建一个空链表或者空的头节点都可以。
2.遍历单链表
3.在遍历单链表的每一个节点时,使用一个临时变量来接受temp节点的next,再将temp节点的next指向新的头节点的next,再将新的头节点的next指向temp节点,这样就完成了一个节点的插入,但是最后还要注意将temp指向临时变量,方便接着循环,直到temp.next == null 为止。
public HeroLinkedList reverse2() {
if(this.head.next == null || this.head.next.next ==null) {
return this;
}
HeroLinkedList newList = new HeroLinkedList();
HeroNode temp = this.head.next;
HeroNode temp1 = null;
while(temp != null){
temp1 = temp.next;
temp.next = newList.head.next;
newList.head.next = temp;
temp = temp1;
}
return newList;
}
4、从尾到头打印单链表
思路:
使用stack栈即可,这里介绍下几个stack中提供的方法
add(E) push(E) 这两个方法基本都差不多,都是添加数据到stack,返回值有点区别。
peek(),这个方法是查看栈顶的数据,并不会移除该数据
pop() 直接取栈顶的数据,同时移除该数据
public void reversePrint() {
if(this.head.next == null) {
System.out.println("链表为空!");
}
Stack<HeroNode> stack = new Stack<>();
HeroNode temp = this.head.next;
while(true) {
if(temp == null) {
break;
}
stack.push(temp);
temp = temp.next;
}
while(!stack.empty()) {
temp = stack.pop();
if(temp==null) {
break;
}
System.out.println(temp);
}
}
5、合并两个单链表,合并之后的单链表依然有序
思路:
直接利用之前写好的有序插入的方法,遍历其中一个单链表,往另一个单链表中有序插入,但是感觉这个方法比较暴力,不知道有没有更好的方法