-
获取链表中倒数第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()); } }
-
-
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。