1.求单链表的有效节点个数(不包括头节点)
public int getLength(){
if (head.next == null){//空链表
return 0;
}
int length = 0;
//定义一个辅助的变量
HeroNode cur = head.next;
while (cur != null){
length++;
cur = cur.next;//遍历
}
return length;
}
}
2.找单链表中的倒数第k个节点(顺数第(length-index+1)个)
/**
* 查找单链表的倒数第k个节点
* @param
* @return
*/
public HeroNode findLastIndexNode(int index){
if (head.next == null){
return null;//没有找到
}
int size = getLength();
//做index有效校验
if (index <= 0 || index > size){
return null;
}
///定义辅助变量,for循环定位到倒数的index
HeroNode cur = head.next;
//从第一个有效节点开始,往后移动size-index次
for (int i = 0;i < size - index; i++){
cur = cur.next;
}
return cur;
}
3.单链表的反转
public void reverseList(){
//如果当前链表为空,或者只有一个节点,无需反转,直接返回
if (head.next == null || head.next.next == null){
return;
}
//定义一个辅助(指针)变量,用来帮助我们遍历原来的链表
HeroNode cur = head.next;
HeroNode next = null;//用来记录当前节点的下一个节点,
// 因为在将当前节点插入到reverseHead节点后面之前,需要将cur指针后移。
// 如果在将当前节点移走之前没有记录下一个节点,整个链表就会断
HeroNode reverseHead = new HeroNode(0,"","");//空头
//遍历原来的链表,每遍历一个节点,就将其取出,并放在新的链表前端
while(cur != null){//遍历未结束
next = cur.next;//先暂时保存当前节点的下一个节点,因为后面需要使用。
cur.next = reverseHead.next;//当前节点指向新头节点的后置节点(绿线)
reverseHead.next = cur;//新头节点指向当前节点(蓝线)
cur = next;//让cur后移
}
//将head.next指向reverseHead.next,实现单链表的反转
head.next = reverseHead.next;//原头节点指向新头节点的后置节点(黄线)
}
4.从尾到头打印单链表【要求方式1:反向遍历。方式2:stack栈】
public void reversePrint(){
if (head.next == null){
return;//空链表无法打印
}
//创建一个栈,将各个节点压入栈中
Stack<HeroNode> stack = new Stack<>();
HeroNode temp = head.next;
//将链表的所有节点压入栈
while(temp != null){
stack.push(temp);
temp = temp.next;
}
//出栈打印
while (stack.size() > 0){
System.out.println(stack.pop());
}
}
5.合并两个有序的单链表,合并之后的链表依然有序
package com.zengwen.linkedlist;
import java.util.List;
public class TestListNode {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(3);
ListNode l3 = new ListNode(5);
l1.next = l2;
l2.next = l3;
l2 = new ListNode(2);
l3 = new ListNode(4);
ListNode l4 = new ListNode(6);
l2.next = l3;l3.next = l4;
System.out.println(l1);
System.out.println(l2);
TestListNode testListNode = new TestListNode();
ListNode l5 = testListNode.mergeTwoLists(l1, l2);
while (l5 != null){
System.out.println(l5.val + "->");
l5 = l5.next;
}
System.out.println(l5);
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode temp = null;
//如果l1链表的值小于l2链表的值
if (l1.val <= l2.val){
//链表l1的
temp = l1;
temp.next = mergeTwoLists(l1.next,l2);
}else{
temp = l2;
temp.next = mergeTwoLists(l1,l2.next);
}
return temp;
}
}
/**
* Definition for singly-linked list
*/
class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}