leetcode 19. Remove Nth Node From End of List 链表

Given a linked list, remove the n-th node from the end of list and return its head.

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.

Follow up:

Could you do this in one pass?

t1 为要删除元素的前一个元素的 next 指针的地址,具体做法是设置一个 ListNode *t2 先让 t2n-1,然后令 t1head 指针的地址,令 t1,t2 同时向后移动直至 t2->next=NULL ,此时 *t1t2 便相差了 n 个元素。

复杂度 O(n)O(n)

/**
 * 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 **t1=&head,*t2=head;
        for(int i=1;i<n;i++)t2=t2->next;
        while(t2->next!=NULL){
            t1=&(*t1)->next;
            t2=t2->next;
        }
        *t1=(*t1)->next;
        return head;
    }
};
posted @ 2020-05-22 08:50  winechord  阅读(70)  评论(0编辑  收藏  举报