[leetcode-]Remove Nth Node From End of List(C)
来源:互联网 发布:java 模块化开发 编辑:程序博客网 时间:2024/06/06 03:10
问题描述:
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,然后当最后一个指针到达null时,此时,第一个指针就是要删除的元素。
代码如下:0ms
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { struct ListNode *prev=head,*next = head; int i; if(n<=0) return head; for(i = 0;i<n;i++){ next = next->next; } if(next==NULL)//到达最后 return head->next; while(next->next!=NULL){ prev = prev->next; next = next->next; } prev->next = prev->next->next; return head;}
0 0
- [C++]LeetCode: 4 Remove Nth Node From End of List
- [leetcode-]Remove Nth Node From End of List(C)
- 【LeetCode-19】Remove Nth Node From End of List(C++)
- 【C++】【LeetCode】19. Remove Nth Node From End of List
- Leetcode c语言-Remove Nth Node From End of List
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- 对一个现成的ts进行pat和pmt表的解析,并提取视频保存到文件中
- Generate Parentheses
- webbench压力测试工具
- 复习三:大数据&分布式
- [LeetCode]Container With Most Water
- [leetcode-]Remove Nth Node From End of List(C)
- 一个程序演示所有的shell编程知识
- Revit 二次开发之安装包的制作
- 不借助第三个变量实现两个变量交换的思考
- Android 实现动态体温计
- JAVA的比较之==
- FBReader 最新源码编译(Windows环境)和研究(一)
- __sync_val_compare_and_swap, 无锁锁
- VS2010 LNK1123: 转换到 COFF 期间失败: 文件无效或损坏 的解决方法