19. Remove Nth Node From End of List题解

来源:互联网 发布:php curl post提交 编辑:程序博客网 时间:2024/05/22 03:07

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.

Subscribe to see which companies asked this question.

题目意思:
给你一个链表,去除掉倒数第n个节点。
解析:
设两个指针 p; q,让 q 先走 n 步,然后 p 和 q 一起走,直到 q 走到尾节点,删除 p->next 即可。
源代码:

#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;}



原创粉丝点击