19:Remove Nth Node From End of List【两指针】【链表】

题目连接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/*题意:删除链表中从最后一个结点向前的第n个结点 */

/**
 *思路:1、两个指针,first和second,让first指针先走n步
 *      2、接着两个指针同时向后移动,当first指向最后一个
 *         结点时,second->next就是要删除的结点
 *
 */


class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *root = new ListNode(0);//root为根结点
        ListNode *second, *first;

        root->next = head;
        first = second = root;

        for(int i = 0; i < n; i ++) { //first指针先走n步
            first = first->next;
        }

        while(first->next != NULL) { //first指针已到链表尾部
            first = first->next;
            second = second->next;
        }
        second->next = second->next->next; //删除second->next结点
        return root->next;
    }
};

  

posted @ 2015-04-07 18:00  天丶下  阅读(94)  评论(0编辑  收藏  举报