赞
踩
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5.
方法一:
1.1、先找出整个链表的长度;
1.2、确定出L-n的长度;
1.3、将链表拼接为L-n长度;
1.4、将L-n的next指向L-n的next的next;
代码:
- public static MontageLinkedList getMontageLink(MontageLinkedList link, int n) {
- MontageLinkedList newLinck = new MontageLinkedList(0);
- newLinck.next = link;
- MontageLinkedList first = link;
- int len = 0;
-
- //求出链表的长度
- while(first != null) {
- len++;
- first = first.next;
- }
-
- //确定l-n之后的剩余节点数
- len = len - n;
- first = newLinck; //这一步也必不可少
- //将L-n剩余的节点个数进行拼接,拼接的终点是l-n的位置
- while(len > 0) {
- len--;
- first = first.next;
- }
-
- //将L-n的位置的指向改为下下一个指针节点
- first.next = first.next.next;
- return newLinck.next;
- }

方法二:
思路:
1.1、确定两个指针;
1.2、第一个指针从1开始走,走n个节点;
1.3、当第一个节点走了n个时,第二个节点也开始走,第一个指针与第二个指针差距n个数;
1.4、当第一个指针走向null时,第二个指针刚好走到第n个位置,此时需要将n位置的next指向n的下下个节点;
1.5、返回最初的链表;
可以看一看leetcode上面的图片:
代码:
- public class MontageLinkedList {
-
- int value;
- MontageLinkedList next;
-
- public MontageLinkedList(int val) {
- value = val;
- }
-
-
- public static void main(String[] args) {
- MontageLinkedList mon1 = new MontageLinkedList(3);
- MontageLinkedList mon2 = new MontageLinkedList(4);
- MontageLinkedList mon3 = new MontageLinkedList(9);
- MontageLinkedList mon4 = new MontageLinkedList(29);
- MontageLinkedList mon5 = new MontageLinkedList(20);
-
- mon1.next = mon2;
- mon2.next = mon3;
- mon3.next = mon4;
- mon4.next = mon5;
-
- MontageLinkedList l = getMontageLink(3, mon1);
- while(l != null) {
- System.out.print(l.value + " ");
- l = l.next;
- }
-
- }
- /**
- * @param n
- * @param li
- * @return
- * 思路:
- * 1、设置两个指针,第一个先走,走到n+1的位置;
- * 2、直到第二个指针开始走,第一个指针与第二个指针之间间隔n个数;
- */
- public static MontageLinkedList getMontageLink(int n, MontageLinkedList li) {
- MontageLinkedList list = new MontageLinkedList(0);
- list.next = li;
- MontageLinkedList first = list;
- MontageLinkedList second = list;
-
- for(int i = 1; i < n + 1; i++) {
- first = first.next;
- }
-
- while(first != null) {
- first = first.next;
- second = second.next;
- }
-
- second.next = second.next.next;
- return list.next;
- }
- }

结果:
3 4 9 20
就这样了~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。