单链表 案例

1、求单链表中有效节点的个数

  代码实现

 1 // 方法:获取单链表的节点的个数(如果是带头节点的链表,需求不统计头节点)
 2     public static int getLength(HeroNode head) {
 3         if (head.next == null) {
 4             return 0;
 5         }
 6         int length = 0;
 7         // 定义一个辅助变量,这里没有统计头节点
 8         HeroNode cur = head.next;
 9         while (cur != null) {
10             length++;
11             cur = cur.next; // 遍历
12         }
13         return length;
14     }

2、查找单链表中的倒数第 K个节点

  代码实现

 1    // 查找单链表中的倒数第 k 个节点
 2     // 1 编写一个方法,接收head 节点,同时接收一个 index
 3     // 2.index 表示是倒数第 index 个节点
 4     // 3.先把链表头从到尾遍历,得到链表的总长度 getlength
 5     // 4.得到size后,从链表的第一个开始遍历(size-length)个,就可以得到
 6     // 5.如果找到了,则返回节点,否则返回 null
 7     public static HeroNode findLastIndexNode(HeroNode head, int index) {
 8         // 判断如果链表为空,返回null
 9         if (head.next == null) {
10             return null; // 没有找到
11         }
12         // 第一次遍历得到链表的长度(节点的个数)
13         int size = getLength(head);
14         // 第二次遍历 size - length 位置,就是倒数第 K 个节点
15         // 先做数据校验
16         if (index <= 0 || index > size) {
17             return null;
18         }
19         // 定义给辅助变量
20         HeroNode cur = head.next;
21         for (int i = 0; i < size - index; i++) {
22             cur = cur.next;
23         }
24         return cur;
25     }

3、单链表的反转

  思路分析图解

  (1)

   (2)

  代码演示

 1 // 将单链表进行反转
 2     public static void reverseList(HeroNode head) {
 3         // 如果当前链表为空或者只有一个节点,无需反转,直接返回
 4         if (head.next == null || head.next.next == null) {
 5             return;
 6         }
 7         // 定义一个辅助指针(变量),帮助我们遍历原来的链表
 8         HeroNode cur = head.next;
 9         HeroNode next = null; // 指向当前节点cur的下一个节点
10         HeroNode reverseHead = new HeroNode(0, "", "");
11         // 遍历原来的链表,每遍历一个节点,就将其取出,并放在新的链表的 reverseHead 的最前端
12         while (cur != null) {
13             next = cur.next; // 先暂时保存当前节点的下一个节点,后面需要使用
14             cur.next = reverseHead.next; // 将 cur的下一个节点指向新的链表的最前端
15             reverseHead.next = cur; // 将 cur 连接到新的链表上
16             cur = next; // 让 cur 后移
17         }
18 
19         // 将head.next 指向 reverseHead.next ,实现单链表的反正
20         head.next = reverseHead.next;
21 
22     }

4、从尾到头打印单链表

  思路分析图解

  代码实现

 1 // 利用栈这个数据结构,将各个节点压入栈中,然后利用栈的先进后出的特点,实现了逆序打印效果
 2     public static void reversePrint(HeroNode head) {
 3         if (head.next == null) {
 4             return; // 空链表,不能打印
 5         }
 6         // 创建一个栈,将各个节点压入栈
 7         Stack<HeroNode> stack = new Stack<HeroNode>();
 8         HeroNode cur = head.next;
 9         // 将链表的所有节点压入栈中
10         while (cur != null) {
11             stack.push(cur);
12             cur = cur.next; // 让 cur 后移
13         }
14 
15         // 将栈中的节点打印,pop
16         while (stack.size() > 0) {
17             System.out.println(stack.pop()); // stack的特点是先进后出
18         }
19     }

5、合并两个有序的单链表,合并之后的链表仍然有序

原文地址:https://www.cnblogs.com/niujifei/p/11563150.html