Q2.2 Find the kth to last element of a singly linked list
2015-01-17 14:57
411 查看
Q: Find the kth to last element of a singly linked list
A:两个指针,第一个指针从头开始,遍历k-1步,第二个指针开始从头遍历,当第一个指针到最后时,第二个指针的元素就是想要的结果。
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; }
相关文章推荐
- 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
- [CareerCup] 2.2 Kth to Last Element of Linked List 链表的倒数第k个元素
- Ch2-2: return the nth to the last node data of a singly linked list
- a linked list, find the node that the last node point to.
- 1、Find the last element of a list.
- Swap kth element from the beginning and kth element from the end of linked list -- Amazon
- Delete Node in the Middle of Singly Linked List
- 69.You need to generate a list of all customer last names with their credit limits from the CUSTOMER
- lintcode-easy-Delete Node in the Middle of Singly Linked List
- linked-list-cycle&&find-peak-element&&intersection-of-two-linked-lists
- LintCode Delete Node in the Middle of Singly Linked List 在O(1)时间复杂度删除链表节点
- 35.两链表的第一个公共结点[Find the first common node of two linked list]
- #372 Delete Node in the Middle of Singly Linked List
- 步步为营VS 2008 + .NET 3.5(7) - LINQ查询操作符之First、FirstOrDefault、Last、LastOrDefault、ElementAt、ElementAtOrDefault、Contains、Any、All、Count、LongCount、Sum、Min、Max、Average、Aggregate、Cast、DefaultIfEmpty、SequenceEqual、OfType、ToArray、ToList、ToDictionary
- 7、步步为营VS 2008 + .NET 3.5(7) - LINQ查询操作符之First、FirstOrDefault、Last、LastOrDefault、ElementAt、ElementAtOrDefault、Contains、Any、All、Count、LongCount、Sum、Min、Max、Average、Aggregate、Cast、DefaultIfEmpty、SequenceEqual、OfType、ToArray、ToList、ToDictionary
- Find the middle point of the linked list
- Find the starting point of a linked list