现在是第二次了,链表的mid题好像相对简单,虽然不是什么很简洁的写法🤪题目链接
解法一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
public static ListNode removeNthFromEnd(ListNode head, int n) { if (head == null){ return head; }else if (head.next == null){ return null; } ListNode dummyNode = new ListNode(0); dummyNode.next = head; ListNode cur = dummyNode; ListNode cur2 = dummyNode; ListNode cur3 = cur2; int size = 0; while (cur.next != null){ size++; cur = cur.next; } size = size+1; int index = size-n; for (int i = 1; i < index; i++) { cur2 = cur2.next; } if (cur2 != null){ cur2.next = cur2.next.next; } return cur3.next;
|
解法二(双指针)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public ListNode removeNthFromEnd(ListNode head, int n){ ListNode dummyNode = new ListNode(0); dummyNode.next = head;
ListNode fastIndex = dummyNode; ListNode slowIndex = dummyNode;
for (int i = 0; i <= n ; i++){ fastIndex = fastIndex.next; }
while (fastIndex != null){ fastIndex = fastIndex.next; slowIndex = slowIndex.next; }
slowIndex.next = slowIndex.next.next; return dummyNode.next; }
|
