首页 > 代码库 > LeetCode: Remove Nth Node From End of List [019]
LeetCode: Remove Nth Node From End of List [019]
【题目】
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个结点
【思路】
维护两个指针p1,p2,初始时都指向首节点。p2结点先向前移动n步,然后两个指针同时向后移动,直至p2指向队尾的空指针。此时p1指向的即为需要删除的指针。为了完成操作,还需要额外维护一个指向p1前一个结点的prev指针。【代码】
/** * 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) { ListNode*prev=NULL; ListNode*p1=head; ListNode*p2=head; int k=0; while(k<n && p2){k++;p2=p2->next;} if(k<n)return head; //链表元素少于n个,则不做删除操作 //定位待待删除元素 while(p2){ prev=p1; p1=p1->next; p2=p2->next; } //删除元素 if(prev)prev->next=p1->next; else head=p1->next; return head; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。