0X01 题目
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
- Given n will always be valid.
- Try to do this in one pass.
0X02 题意
题目比较简单,给定一个链表和一个数字n,从链表中删除倒数第n个元素。
0X03 题解
1.解法一(Cathy:C++)
yyj的解法,大致思路就是先用一个循环求出链表的总长度m,然后再根据n找到需要删除的元素,删除即可。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if ((head == NULL) or (head->next == NULL))
{
return NULL;
}
int m = 1;
ListNode* lc;
lc = head->next;
while (lc != NULL)
{
m++;
lc = lc->next;
}
if (n == m)
{
return head->next;
}
lc = head;
int i = 0;
while (i < m - n - 1)
{
lc = lc->next;
i++;
}
lc->next = lc->next->next;
return head;
}
};
2.解法二(Dante:Java)
我第一反应想出来的方法,最初有一些边界值没考虑到位,被Leetcode干掉了,然后加了一个头指针就解决了。
大致思路就是有两个指针fast和slow,fast比slow的位置早n个,然后开始循环,当slow指向最后一个元素的时候,slow就找到了该被删除的元素。
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode start = new ListNode(0);
ListNode slow = start, fast = start;
slow.next = head;
for(int i=1; i<=n+1; i++) {
fast = fast.next;
}
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return start.next;
}
}