Easy-题目44:19. Remove Nth Node From End of List
来源:互联网 发布:边际递减效应爱情知乎 编辑:程序博客网 时间:2024/06/18 22:27
题目原文:
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.
题目大意:
给出一个单链表,删除倒数第n个节点。
题目分析:
用两个指针,第一个指针p1指向头结点,然后第二个节点p2指向p1之后第n个节点(向右滑动n次)。然后并行向右滑动两个指针,直到p2为最后一个节点(p2->next==NULL),此时p1指向待删除节点的前一个节点,令p1=p1->next即可。
源码:(language:c)
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { if (!head) return NULL; struct ListNode *p1 = head; struct ListNode *p2 = head; for(int i = 0; i < n; i++) p2 = p2->next; if(!p2) return head->next; while(p2->next) { p1 = p1->next; p2 = p2->next; } p1->next=p1->next->next; return head;}
成绩:
0ms,beats 19.70%,众数0ms,80.30%
Cmershen的碎碎念:
本题有一个需要讨论的地方,就是在p2向右滑动n步的时候,有可能滑到最后一个节点的后面(即null),此时说明要删除的是头节点,直接返回head->next即可。
0 0
- Easy-题目44:19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List [easy] (Python)
- 19. Remove Nth Node From End of List (Easy)
- [Leetcode 19, Easy] Remove Nth Node From End of List
- Leetcode[Easy] - Remove Nth Node From End of List
- [Leetcode 19, Easy] Remove Nth Node From End of List
- <LeetCode><Easy> 19 Remove Nth Node From End of List
- Remove Nth Node From End of List(easy)
- LeetCode算法题目:Remove Nth Node From End of List
- [leetcode] 19. Remove Nth Node From End of List python实现【easy】
- Leetcode 19. Remove Nth Node From End of List (Easy) (cpp)
- 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
- 【HDU】 1397 Goldbach's Conjecture
- 数据结构-线性表
- maven整合spring+springMvc+Mybatis+Mysql
- 让爬虫更加友好
- C++生成随机数
- Easy-题目44:19. Remove Nth Node From End of List
- 客户端调用服务端接口减少请求数据容量的优化例子
- 安卓小案例收集二
- poj1984 Navigation Nightmare(带权并查集)
- [bzoj2818]gcd
- java的并发测试
- READING NOTE: Semantic Object Parsing with Graph LSTM
- 基因数据处理43之mango之503错误
- 2016SDAU课程练习三1016