leetcode---remove-nth-node-from-end-of-list---链表
来源:互联网 发布:声明一维数组大小 编辑:程序博客网 时间:2024/06/05 03:45
Given a linked list, remove the n th 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.
/** * 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) return NULL; ListNode *cur = head; int cnt = 0; while(cur) { cur = cur->next; cnt++; } if(cnt == 1) return NULL; int m = cnt - n; if(m == 0) // 如果删除的是头部 { return head->next; } cur = head; cnt = 0; while(cnt < m-1) { cur = cur->next; cnt++; } ListNode *p = cur->next; if(p) cur->next = p->next; else // 如果删除的是尾部 cur->next = NULL; delete p; return head; }};
阅读全文
0 0
- [leetcode] 【链表】19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List(链表)
- leetcode---remove-nth-node-from-end-of-list---链表
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- (转载)JVM基础知识
- 【共享打印机遇到的各种问题】局域网内连接共享打印机—如何不用打印机路由,在多台电脑使用打印机
- 算法题:从数组找数字(网易2017校园招聘)
- Python 中的实用数据挖掘
- WebService详解
- leetcode---remove-nth-node-from-end-of-list---链表
- [LeetCode]405. Convert a Number to Hexadecimal
- ODBC连接数据库实例
- 深入理解java虚拟机-第二章:垃圾收集算法
- ue4 weapon
- android事件传递全解析
- R_ggplot2作图原理
- hdu 6178 Monkeys 贪心
- 简单约瑟夫环 -mobai_dalao