删除链表中倒数第n个节点
2017-03-22 22:17
295 查看
1、问题描述
给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。给出链表1->2->3->4->5->null和
n = 2.删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.
2、实现思路
先计算链表的长度,用for循环找到要删的节点, 要考虑链表长度<n和当长度=n时,实际上删除的是头结点 。
3、代码
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *x = head;
ListNode *l = head;
int count=0;
while(head!=NULL){
head = head->next;
count++;
}
if(count<n)
return x;
if(count>n)
{
for(int i=1;i<(count-n);i++)
{
l = l->next;
}
l->next=l->next->next;
return x;
}
if(count==n){
return x->next;
}
}
};
4、感想
本题和链表倒数第n个节点想法相似,只是多了删除操作,并且要注意链表长度比n短和链表只有头结点终端节点情况。
给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。给出链表1->2->3->4->5->null和
n = 2.删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.
2、实现思路
先计算链表的长度,用for循环找到要删的节点, 要考虑链表长度<n和当长度=n时,实际上删除的是头结点 。
3、代码
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *x = head;
ListNode *l = head;
int count=0;
while(head!=NULL){
head = head->next;
count++;
}
if(count<n)
return x;
if(count>n)
{
for(int i=1;i<(count-n);i++)
{
l = l->next;
}
l->next=l->next->next;
return x;
}
if(count==n){
return x->next;
}
}
};
4、感想
本题和链表倒数第n个节点想法相似,只是多了删除操作,并且要注意链表长度比n短和链表只有头结点终端节点情况。
相关文章推荐
- 删除链表中倒数第n个节点
- Remove Nth Node From End of List 删除链表倒数第N个节点
- 删除链表的倒数第N个节点
- leetcode-19. Remove Nth Node From End of List(删除链表倒数第N个节点)
- [LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点
- 删除链表中倒数第n个节点
- leetcode:Remove Nth Node From End of List(删除链表倒数第n个节点)【面试算法题】
- 删除链表中倒数第n个节点
- 删除单向链表倒数第n个节点
- lintcode删除链表中倒数第n个节点
- Leet Code 19 删除链表中倒数第n个节点 - Java
- python_lintcode_372在O(1)时间复杂度删除链表节点_174删除链表中倒数第n个节点
- LintCode-174.删除链表中倒数第n个节点
- lintcode ----删除链表中倒数第n个节点
- Java实现-删除链表中倒数第n个节点
- 题目:删除链表中倒数第n个节点
- 删除链表中倒数第n个节点
- 删除链表中倒数第N个节点
- 删除链表中倒数第n个节点
- Lintcode174——删除链表中倒数第n个节点