LeetCode之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,

   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.
Try to do this in one pass.

【题意】

给你一个链表,去除掉倒数第n个节点。

【分析】

设两个指针 p; q,让 q 先走 n 步,然后 p 和 q 一起走,直到 q 走到尾节点,删除 p->next 即可。

【代码】

/*********************************
*   日期:2014-01-29
*   作者:SJF0115
*   题号: Remove Nth Node From End of List
*   来源:http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;

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 || n <= 0){
            return head;
        }
        ListNode *dummy = (ListNode*)malloc(sizeof(ListNode));
        dummy->next = head;

        ListNode *temp = NULL;
        ListNode *pre = dummy,*cur = dummy;
        //cur先走N步
        for(int i = 0;i < n;i++){
            cur = cur->next;
        }
        //同步前进直到cur到最后一个节点
        while(cur->next != NULL){
            pre = pre->next;
            cur = cur->next;
        }
        //删除pre->next
        temp = pre->next;
        pre->next = temp->next;
        delete temp;
        return dummy->next;
    }
};
int main() {
    Solution solution;
    int A[] = {1,2,3,4,5};
    ListNode *head = (ListNode*)malloc(sizeof(ListNode));
    head->next = NULL;
    ListNode *node;
    ListNode *pre = head;
    for(int i = 0;i < 5;i++){
        node = (ListNode*)malloc(sizeof(ListNode));
        node->val = A[i];
        node->next = NULL;
        pre->next = node;
        pre = node;
    }
    head = solution.removeNthFromEnd(head->next,4);
    while(head != NULL){
        printf("%d ",head->val);
        head = head->next;
    }
    return 0;
}





LeetCode之Remove Nth Node From End of List

上一篇:动态断言与静态断言


下一篇:LeetCode之Rotate List