Q2.2 Find the kth to last element of a singly linked list
来源:互联网 发布:如何自学seo 编辑:程序博客网 时间:2024/05/17 20:28
Q: Find the kth to last element of a singly linked list
A:两个指针,第一个指针从头开始,遍历k-1步,第二个指针开始从头遍历,当第一个指针到最后时,第二个指针的元素就是想要的结果。
#include <iostream>using namespace std;struct ListNode { int val;ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *init(int a[], int n) { ListNode *head = NULL; ListNode *p = NULL; for (int i = 0; i < n; i++) { ListNode *cur = new ListNode(a[i]); if (i == 0) { head = cur; p = cur; } p->next = cur; p = cur; } return head; } int kthToLast(ListNode *head, int k) { ListNode *first = head; ListNode *second = head; for (int i = 0; i < k; i++) { first = first->next; } while (first) { first = first->next; second = second->next; } return second->val; } int main() { int a[10] = {1,5,2,6,7,4,6,2,8,9};ListNode *head = init(a, 10);cout<<kthToLast(head, 2)<<endl;return 0; }
0 0
- Q2.2 Find the kth to last element of a singly linked list
- To find the kth to Last Element of a Singly Linked List
- Find the nth to last element of a singly linked list
- [CrackCode] 2.2 Find the nth to last element of a singly linked list
- 【10】Find nth to last element of a singly linked list
- Ch2-2: return the nth to the last node data of a singly linked list
- 1、Find the last element of a list.
- How do you find length of a Singly Linked list
- Swap kth element from the beginning and kth element from the end of linked list -- Amazon
- 1007. Find the middle element in a Linked List
- LinkedList---Delete Node in the Middle of Singly Linked List
- #372 Delete Node in the Middle of Singly Linked List
- Delete Node in the Middle of Singly Linked List
- find the kth largest element in a list and find the first k largest elements in a list
- Get middle element of a linked-list
- Reverse a singly linked list python
- quick select to find the kth smallest element in array
- Convert Sorted List to Binary Search Tree -- leetcodeGiven a singly linked list where elements are s
- SQL学习笔记之数据库专题(四):浅谈JDBC用法
- 关于双重指针的用法
- C++重载,重写,重定义
- 开放源代码GIS资源集锦
- 方便快捷管理wifi
- Q2.2 Find the kth to last element of a singly linked list
- Windows 最佳化(現已不適用)
- atitit.安全的签名摘要 算法attilax总结
- 获得文件夹内所有文件的文件名列表
- windows系統目錄功能
- Java脚本语言引擎接口
- codevs1253 超级市场
- 面试Android工程师遇到的面试题
- 多文件上传 iOS