Remove Nth Node From End of List

来源:互联网 发布:ios6卡顿优化 编辑:程序博客网 时间:2024/04/30 13:16

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

设置双指针p,q,中间间隔n-1,同时移动,q到最后时,p为要删除的节点

/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
               if(head == NULL)
               return NULL;
               ListNode *p = head,*q = head;
               // int t = 0;
               if(n == 1){
                   q = head->next;
                   if(q == NULL)
                   return NULL;
                   while(q->next){
                       p = p->next;
                       q = q->next;
                   }
                   p->next = NULL;
                   return head;
               }
               else if(n != 1){
                   while(q){
                         q = q->next;
                         t++;
                         if(t == n-1)
                         break;
                   }
               }
               while(q->next){
                       p  =  p->next;
                       q  =  q->next;
               }
               p->val = p->next->val;
               p->next = p->next->next;
               return head;
    }
};

原创粉丝点击