[LeetCode-Algorithms-19] "Remove Nth Node From End of List" (2017.11.16-WEEK11)

来源:互联网 发布:修改图片软件 编辑:程序博客网 时间:2024/06/05 04:11

题目链接: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.


(1)思路:注意只能进行一次遍历就得出结果。那么可以使用两个指针始终保持n距离,当一个指针移动到链表尾部时,另外一个指针指向要删除元素的前一个,那么删除它的下一个节点。

(2)代码:

/** * 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) {        if (head->next==NULL) return NULL;              ListNode *p = head, *q = head;                 while(n--) q = q->next;                         if (q == NULL) return head->next;        while(q->next) {                                     q = q->next;            p = p->next;        }        p->next = p->next->next;                    return head;    }};

(3)提交结果:

这里写图片描述

阅读全文
0 0
原创粉丝点击