Remove Nth Node From End of List

来源:互联网 发布:c语言输出心形图案 编辑:程序博客网 时间:2024/06/05 19:45

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)主要是边界问题

1、{1},1的情况下,处理的时候,我们当

k>=0
的时候也就是要删除第一个元素,比较特殊,因此得特别对待。


#include <iostream>using namespace std;struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};ListNode *removeNthFromEnd(ListNode *head, int n) {ListNode *p = head;int k = n-1;while(p->next!=NULL && k>=0){p = p->next;k--;}if(k>=0){head = head->next;return head;}ListNode *q = head;while(p->next!=NULL){p = p->next;q = q->next;}q->next = q->next->next;return head;}int main(void){ListNode *head;ListNode *node = (ListNode *)malloc(sizeof(ListNode));node->val = 1;node->next = NULL;head = node;removeNthFromEnd(head, 1);system("pause");return 0;}


0 0