leetcode: Remove Nth Node From End of List

来源:互联网 发布:windows隐藏任务栏图标 编辑:程序博客网 时间:2024/04/30 20:16

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.

两个指针,快的先走n步,然后一起走,快的走到NULL,删除慢的指向的节点

/** * 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) {        if( head == NULL)            return head;        int cnt = 0;        ListNode *p = head;        while(p){            ++cnt;            p = p->next;        }        if( cnt < n)            return head;        p = head;        while( n){            p = p->next;            --n;        }        ListNode *q = head, *pre = NULL;        while(p){            p = p->next;            pre = q;            q = q->next;        }        if( pre == NULL)            return head->next;        pre->next = q->next;        delete q;        return head;    }};


0 0
原创粉丝点击