lintcode 174. 删除链表中倒数第n个节点

给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。

样例
Example 1:
	Input: list = 1->2->3->4->5->null, n = 2
	Output: 1->2->3->5->null


Example 2:
	Input:  list = 5->4->3->2->1->null, n = 2
	Output: 5->4->3->1->null

挑战
O(n)时间复杂度

注意事项
链表中的节点个数大于等于n
/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @param n: An integer
     * @return: The head of linked list.
     */
    ListNode * removeNthFromEnd(ListNode * head, int n) {
        // write your code here
        ListNode*p=new ListNode;
        p->next=head;
        ListNode*first=p;
        for (int i = 1; i <= n+1; i++) {
            /* code */
            first=first->next;
        }
        ListNode*second=p;
        while(first)
        {
            first=first->next;
            second=second->next;
        }
        second->next=second->next->next;
        return p->next;
    }
};
发布了330 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/103916750