加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

1.4.1 单链表练习

发布时间:2020-12-14 04:41:43 所属栏目:百科 来源:网络整理
导读:获取单链表节点的有效个数(不统计头结点) 思路分析 遍历链表,统计个数 代码实现 // 获取链表的有效节点个数(不包含头节点)public static int getLength(HeroNode head) { int sum = 0; HeroNode temp = head.next; while (null != temp) { sum++; temp =
  • 获取单链表节点的有效个数(不统计头结点)

    • 思路分析

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

      • // 获取链表的有效节点个数(不包含头节点)
        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());
           }
        }
        

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读