LeetCode 19. Remove Nth Node From End of List
来源:互联网 发布:淘宝资产拍卖 编辑:程序博客网 时间:2024/04/30 11:37
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.
一、算法分析
(1)单链表同样不带头结点;(2)如果删除的是头结点,注意这种情况单独讨论;(3)算法思想就是设置两个指针,第一个指针走n步时,第二个指针才刚刚开始走。这样第一个指针到达终点时,第二个指针恰好在倒第N个;删除指针还是用了pre,其实可以p->val=p->next->val;但是这里还是有p->next是否为NULL的问题,要记得判断,我就采用pre直接删除了。
二、C语言实现
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { struct ListNode *p,*q,*pre; p=head; while(n--){ p=p->next; } if(p==NULL){//表示要删除第一个结点 return head->next; } pre=head; q=head->next; while(p->next!=NULL){ p=p->next; pre=q; q=q->next; } pre->next=q->next; return head;}
0 0
- 19. Remove Nth Node From End of List leetcode list
- [LeetCode]19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List Leetcode Python
- LeetCode --- 19. Remove Nth Node From End of List
- LeetCode 19.Remove Nth Node From End of List
- [Leetcode] 19. Remove Nth Node From End of List
- [leetcode] 19.Remove Nth Node From End of List
- <LeetCode OJ> 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List LeetCode
- leetcode 19. Remove Nth Node From End of List
- [LeetCode OJ] 19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- Leetcode:19. Remove Nth Node From End of List(JAVA)
- leetcode 19. Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List
- 【LeetCode】19. Remove Nth Node From End of List
- leetcode 19.Remove Nth Node From End of List
- 【android】在Activity中重写onNewIntent方法
- JavaScript实现模糊匹配
- 学习OpenCV2——抠图及setmousecallback说明
- 写项目
- gitlab 7.4.5 nginx apache 配置
- LeetCode 19. Remove Nth Node From End of List
- 非UI线程可不可以更新UI(二)
- 网页中添加打印导出保存
- nagios插件之登陆router监控vrrp状态
- Centos6.7 Protocol buffer(Python)安装注意事项
- 排序算法大全
- ios 生命周期初步介绍
- 手动更新nessus的plugins
- cocos2dx LabelTTF 标签