【leetcode】Remove Nth Node From End of List

来源:互联网 发布:知乎数据库的数据类型 编辑:程序博客网 时间:2024/05/16 02:24

Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.
For example,
这里写图片描述
思路:
用双指针的方法,一个走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 *p1,*p2,*temp;        p1=head;        p2=head;        for(int i=0;i<n;i++)        {            p1=p1->next;        }        while(p1)        {            p1=p1->next;            temp=p2;            p2=p2->next;        }        if(p2==head)            head=head->next;        else        {            temp->next=p2->next;        }        return head;    }};
0 0