19. Remove Nth Node From End of List
来源:互联网 发布:linux怎么复制命令 编辑:程序博客网 时间:2024/06/08 03:36
题目
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.
对链表遍历一遍,假设链表规模为k,前n步内只移动p指针,然后移动k-n次t指针,则循环结束后t指向倒数第n+1个元素,其中h指针保证t在第n+1次循环时保持指向head不动,并且如果h不发生变化证明需要删去的是头结点,返回head->next。
/** * 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; ListNode* h=head; ListNode* t=head; ListNode* p=head; int i=0; while(p!=NULL) { if(i<n) { p=p->next; i++; } else { t=h; h=h->next; p=p->next; } } if(h==head) return head->next; t->next=t->next->next; return head; }};
0 0
- 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
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- HP服务器 PPM灯报警
- Android Studio 2.0编译报错解决方法
- Container exited with a non-zero exit code 127
- 启动hadoop NoClassDefFoundError: javax/net/SocketFactory
- Hive WARNING: org.apache.hadoop.metrics.jvm.EventCounter is deprecated
- 19. Remove Nth Node From End of List
- Navicat for mysql 远程连接mysql数据库问题 1130报错
- svn服务器搭建
- (转载)RCNN,SPPNet,Fast_RCNN,Faster_RCNN
- linux系统查看内存使用率
- hbase.mapred.TableMapReduceUtil.initCredentials
- CodeForces - 660A Co-prime Array (模拟)
- 配置hadoop-1.2.1 eclipse开发环境 Run as hadoop
- eclipse hadoop设置报错 9000 failed on connection exception