1.4.1 单链表练习

  • 获取单链表节点的有效个数(不统计头结点)

    • 思路分析

      • 遍历链表,统计个数
    • 代码实现

      • // 获取链表的有效节点个数(不包含头节点)
        public static int getLength(HeroNode head) {
           int sum = 0;
           HeroNode temp = head.next;
           while (null != temp) {
              sum++;
              temp = temp.next;
           }
           return sum;
        }
        
  • 获取链表中倒数第n个节点

    • 思路分析

      • 先获取链表的长度,再遍历length-index次(相当于指针后移)
    • 代码实现

      • // 获取链表的倒数第n个节点
        public static HeroNode findLastIndexNode(HeroNode head, int index) {
           // 先获取链表节点总数 再遍历 length - index 次
           int length = getLength(head);
           if (index <= 0 || index > length) {
              return null;
           }
           HeroNode temp = head.next;
           // 例如有3 个元素 找倒数第1个 length - size = 2 指针只需移动两次(初始指向了第一个节点)
           for (int i = 0; i < length - index; i++) {
              temp = temp.next;
           }
           return temp;
        }
        
  • 反转单链表(采用头插法)

    • 思路分析

      • 遍历链表,将拿到的每一个元素插入到临时节点之后,之前插入的节点都会后移
      • 最后将临时节点替换成原始的头节点
    • 代码实现

      • // 反转单链表(采用类似头插法的样子)
        public static void reverseList(HeroNode head) {
           // 类似于临时头节点
           HeroNode reverseNode = new HeroNode(0, "", "");
           HeroNode currentNode = head.next; // 当前节点
           HeroNode nextNode; // 下一个节点
           while (null != currentNode) {
              nextNode = currentNode.next;
              // 调整链表 (不调整也行) head.next = nextNode;
              // 采用头插(顺序不能变,否则会丢失节点)
              currentNode.next = reverseNode.next;
              reverseNode.next = currentNode;
              // 移动指针
              currentNode = nextNode;
           }
           // 全部完成后 移动头节点
           head.next = reverseNode.next;
        }
        
  • 逆序打印单链表(使用栈)

    • 思路分析

      • 方式一:将链表进行反转,再进行打印(会破坏链表的原始结构,后面再用该链表则是错的)
      • 方式二:采用栈,将链表中的元素压入栈中,再将栈中的元素进行打印(栈:先进后出)
    • 代码实现

      • // 逆序打印单链表,不破坏链表的结构(使用栈,先进后出)
        public static void reversePrint(HeroNode head) {
           HeroNode currentNode = head.next;
           Stack<HeroNode> heroNodeStack = new Stack<>();
           while (null != currentNode) {
              heroNodeStack.push(currentNode);
              currentNode = currentNode.next;
           }
           while (heroNodeStack.size() > 0) {
              System.out.println(heroNodeStack.pop());
           }
        }
        
posted @ 2020-08-27 17:54  xiaokantianse  阅读(143)  评论(0编辑  收藏  举报