LeetCode(Remove Nth Node From End of List)删除链表倒数第n个节点
2014-04-15 03:12
751 查看
题目要求:
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Note:
Given n will always be valid.
Try to do this in one pass.
代码:
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.
代码:
class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { if(head == NULL) return NULL; if(n <= 0) return head; ListNode* first_ptr = head, *second_ptr = head; for(size_t i = 0; i < n - 1; ++i) { if(first_ptr->next != NULL) first_ptr = first_ptr->next; else return head; } if(first_ptr->next == NULL)//如果要删除的是头结点 { ListNode* node = head; head = head->next; delete node; node = NULL; return head; } ListNode* pre = head;//保存要删除节点的前一个节点 if(first_ptr->next != NULL) { first_ptr = first_ptr->next; second_ptr = second_ptr->next; } while(first_ptr->next != NULL) { first_ptr = first_ptr->next; second_ptr = second_ptr->next; pre = pre->next; } pre->next = second_ptr->next; delete second_ptr; second_ptr = NULL; return head; } };
相关文章推荐
- 【LeetCode题解】19_删除链表的倒数第N个节点(Remove-Nth-Node-From-End-of-List)
- [LeetCode-19] Remove Nth Node From End of List(删除链表中倒数第N个节点)
- [LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点
- leetcode-19. Remove Nth Node From End of List(删除链表倒数第N个节点)
- leetcode:Remove Nth Node From End of List(删除链表倒数第n个节点)【面试算法题】
- 【LeetCode】Remove Nth Node From End of List 删除链表中倒数第n个节点- Easy +
- [C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)
- [LeetCode] 19. Remove Nth Node From End of List 删除链表的倒数第N个节点 @python
- [LeetCode] 19. Remove Nth Node From End of List 移除链表倒数第N个节点
- 【Leetcode】19. Remove Nth Node From End of List - 删掉链表倒数第n个节点
- 174. 删除链表中倒数第n个节点 (remove-nth-node-from-end-of-list)(c++)----lintcode面试题之链表
- Remove Nth Node From End of List 删除链表倒数第N个节点
- LeetCode 19. Remove Nth Node From End of List--删除链表的倒数第n个结点
- leetCode 19.Remove Nth Node From End of List(删除倒数第n个节点) 解题思路和方法
- Leetcode Remove Nth Node From End of List 删除链表倒数第n个元素
- [Leetcode] remove nth node from the end of list 删除链表倒数第n各节点
- Remove Nth Node From End of List 链表删除倒数第N个元素@LeetCode
- #19 Remove Nth Node From End of List(删除链表倒数第N个节点)
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- [LeetCode] Remove Nth Node From End of List 移除链表倒数第N个节点