To find the kth to Last Element of a Singly Linked List
2015-07-24 22:23
393 查看
To find the kth to Last Element of a Singly Linked List
To find the kth to Last Element of a Singly Linked ListWeb Link
Description
Code - C
Tips
Web Link
NoneDescription
Write a program to find the kth to Last Element of a Singly Linked ListFor example:
Original List : ->1->2->8->3->7->0->4
Output : 3rd Element from the end is : 7
Code - C++
片段[code]ListNode* findkthtolast(ListNode *head, int k) { ListNode* runner = head; ListNode* chaser = head; if (head == NULL || k < 0) { return NULL; } for (int i = 0; i < k; i++) { runner = runner->next; } while (runner != NULL) { chaser = chaser->next; runner = runner->next; } return chaser; }
完整(包括测试)
[code]#include<iostream> using namespace std; class ListNode{ public: int val; ListNode* next; ListNode(const int val, ListNode* nextNode = NULL) :val(val), next(nextNode){ } }; ListNode* findkthtolast(ListNode *head, int k) { ListNode* runner = head; ListNode* chaser = head; if (head == NULL || k < 0) { return NULL; } for (int i = 0; i < k; i++) { runner = runner->next; } while (runner != NULL) { chaser = chaser->next; runner = runner->next; } return chaser; } void findkthtolasttest() { ListNode* head = new ListNode(1, NULL); ListNode* node = head; node->next = new ListNode(2, NULL); node = node->next; node->next = new ListNode(8, NULL); node = node->next; node->next = new ListNode(4, NULL); node = node->next; node->next = new ListNode(7, NULL); node = node->next; node->next = new ListNode(0, NULL); node = node->next; node->next = new ListNode(4, NULL); node = node->next; node->next = NULL; cout << findkthtolast(head,3)->val << endl; } int main() { findkthtolasttest(); return 0; }
Tips
None相关文章推荐
- 事件冒泡和事件捕获
- ch8 对象的容纳
- 机器学习-组合算法总结
- ch6 类再生
- Openssl pkcs7命令
- 关于将navigationBar的背景设置成透明,并且让navigationItem展示出来
- 股票学习(技术指标)
- 大数运算问题
- hdu 1323 Perfection
- ch5 隐藏实施过程
- ch3 控制程序流程
- Leetcode 5 Longest Palindromic Substring
- poj3468 A Simple Problem with Integers
- 素数距离问题
- hihoCoder - 1079 - 离散化 (线段树 + 离散化)
- OpenCV图像处理篇之腐蚀与膨胀
- 多线程编程模型
- ch4 初始化和清除
- 《C语言及程序设计》实践参考——分数的累加
- 升级 DNX 和 DNVM