LintCode 174:Remove Nth Node From End of List
来源:互联网 发布:网络打印机安装失败 编辑:程序博客网 时间:2024/06/08 09:09
Description:
Given a linked list, remove the nth node from the end of list and return its head.
Note:
需要注意的边界情况:
当需要删除的结点是head结点时,head会发生改变。
当n超过结点个数时,表明没有需要删除的结点。
Code:
/** * 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) { // write your code here int i; ListNode* first = head; ListNode* second = head; bool flag = false; for(i=0;i<n-1;i++){ if(first) first=first->next; else break; } if(i<n-1||!first) return head; while(first->next&&first->next->next){ first=first->next; second=second->next; flag = true; } ListNode * deleted; if(!flag){ deleted = head; head=head->next; } else{ deleted = second->next; second->next = deleted->next; } delete deleted; return head; }};
阅读全文
0 0
- Lintcode LinkedList 174 Remove Nth Node From End of List
- LintCode 174:Remove Nth Node From End of List
- [Lintcode]Remove Nth Node From End of List
- lintcode: Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- jsp中使用frame
- Oracle使用sqlplus能连接但是SQL Developer连接失败提示IO错误解决方法
- 匿名内部类的使用
- 《深入理解计算机系统》(原书第三版)家庭作业第三章(3.59)解答
- AsyncTask源码分析
- LintCode 174:Remove Nth Node From End of List
- CSS基础(一)--选择器与权重计算
- mysql面试--数据库优化
- C++初始化列表和构造函数体的区别
- Algorithm Notes (六)Linear List
- ios 上传下载
- Scikit-Learn框架
- Unity协同使用初步总结(StartConroutine_IEnumerator & IEnumeratable)
- Ubuntu Server 命令行下显示中文乱码(菱形)解决办法