LeetCode(19) Remove Nth Node From End of List
2015-08-08 16:38
225 查看
题目
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,要求删除链表中倒数第n个结点,返回链表头结点。题目不难,主要是必须考虑周全;
head==NULL || n==0,则直接返回head
链表中结点总数count < n,则直接返回head
链表中结点总数count == n,则head=head->next,返回head
删除中间或尾结点,即删除正序第count-n+1 个结点,将倒序改为正序处理
AC代码
/** * 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 == NULL || n == 0 ) return head; //计算链表中的结点个数 int count = 0; ListNode *p = head; while (p) { count++; p = p->next; } //链表中的结点个数小于要删除的倒数第n个 if (count < n) { return head; } else if (count == n) { ListNode *tem = head; head = head->next; delete tem; } else{ ListNode *p = head, *q = p->next; int i = 1; while (i < (count - n) && q->next!=NULL) { p = p->next; q = q->next; i++; } p->next = q->next; delete q; } return head; } };
GitHub测试程序源码
相关文章推荐
- LeetCode(19) Remove Nth Node From End of List
- 在64位ubuntu14.04上安装校园客户端iNodeClient
- Node安装之windows篇
- node.js调用bat
- nodejs中Buffer的创建和转换
- Node.js开发入门—Express里的路由和中间件
- [leedcode 222] Count Complete Tree Nodes
- LeetCode222 Count Complete Tree Nodes
- 【leetcode每日一题】NO19.Remove Nth Node From End of List
- 将Visual Studio打造成为Node.js IDE
- npm常用命令->nodejs
- nodejs配置与入门
- node.js 事件
- node.js 数组
- (medium)LeetCode 222.Count Complete Tree Nodes
- node msgpack5 数据传输 简单实现
- nodejs之socket.io模块——实现了websocket协议
- log4js-Node.js中的日志管理模块使用与封装【转】
- 47. Element isSameNode() 方法
- 46. Element isEqualNode() 方法