【转载请注明】http://www.cnblogs.com/igoslly/p/8672656.html

看一下题目:

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个元素

注意:

1、n值有效

2、尝试一遍结束

思路1:

1、先计算链表的总长度,遍历一次

2、得到总长度 length/cnt,计算出倒数第n个元素的位置,再遍历到该位置

实现方法1:

由于题目涉及到 [1],n=1的情况,直接返回NULL,如果依旧使用 ListNode * p = head 的遍历,在语句 p->next=p->next->next; 需要额外添加判断语句,否则会报错;

我们这里额外定义了无意义的 ListNode *res 结果结点,next 指向head,巧妙地避免上类情况,结果 return res->next。

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *res=new ListNode();
res->next=head;
ListNode *p=head;
int cnt=; // 链表计数
while(p){
cnt++;
p=p->next;
} p=res;
// 位置从1-cnt,倒数第n个数,为cnt-n+1
for(int i=;i<cnt-n+1;i++){
p=p->next;
}
p->next=p->next->next;
return res->next;
}
};

思路2:

当然题目要求,这道题自然有遍历一遍的方法

要恰好地得到倒数第n个结点位置,那么需要增加临时指针 *p1 , *p2,使两者保持n的距离

那么当 p1 达到末尾时,p2 即指向被删除结点

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *res=new ListNode();
res->next=head;
ListNode *p=res;
// head 做先指针,先走n布
while(n--){head=head->next;}
// head和p保持n步距离,直到head到末尾NULL
while(head!=NULL){
head=head->next;
p=p->next;
}
// 删除结点
p->next=p->next->next;
return res->next;
}
};

最新文章

  1. zeroclipboard浏览器复制插件使用记录
  2. Google C++单元测试框架GoogleTest---GTest的Sample1和编写单元测试的步骤
  3. 镁光c400-MTFDDAK064M固态硬盘更新固件
  4. (转)Sqoop中文手册
  5. Visual studio 生成事件的使用 、xcopy 实现 dll 复制操作、
  6. TypeScript - 基本类型系统
  7. ofbiz进击 第六节。 --OFBiz配置之[widget.properties] 配置属性的分析
  8. IE10 下兼容性问题
  9. Intellij IDEA Maven创建web项目
  10. Java 线程的状态
  11. [HOWTO] Install Sphinx for A Script Pro
  12. Leetcode 实施细节 Rotate Image
  13. PHP安装文件的审计
  14. 异常:Error resolving template &quot;xxx&quot;, template might not exist or might not be accessible...解决办法
  15. mybatis源码解析之Configuration加载(五)
  16. Windows下android模拟器环境搭建
  17. Python实现百度贴吧自动顶贴机
  18. ASP.NET MVC 4 (十一) Bundles和显示模式
  19. get return value of python in shell
  20. 真机调试傻瓜图文教程(Xcode6.4)

热门文章

  1. Linux之强大的selinux
  2. PAT 1107 Social Clusters
  3. Package pdftex.def Error: PDF mode expected, but DVI mode detected!
  4. nyoj_513_A+B Problem IV_20130131532
  5. WeX5 IDE 手机移动开发+JAVA +大数据
  6. HIHO 16 B
  7. JAVA模拟登录实例
  8. CentOS出错You don&amp;#39;t have permission to access on this server
  9. Apache server配置
  10. Myeclipse中解决spring配置文件无提示问题