leetcode 19 Remove Nth Node From End of List

来源:互联网 发布:学生信息管理系统java 编辑:程序博客网 时间:2024/06/06 05:29

问题

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

解法

设置两个指针,第一个指向第一个,第二个指向第n+1个,这样同时向后移动两个指针,当第二个到尾部时,第一个正好在要删除的位置的前一个。
小tips:在链表头上加一个头结点, 就不用考虑删除链表头的问题了。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* removeNthFromEnd(ListNode* head, int n) {        ListNode Head = ListNode(0);        Head.next = head;        ListNode* first = &Head;        ListNode* sec = &Head;        for (int i=0; i<n+1; i++)            sec = sec->next;        while(sec) sec= sec->next, first= first->next;        ListNode* del = first->next;        first->next = first->next->next;        delete del;        return Head.next;    }};
0 0
原创粉丝点击