2.2 实现一个算法,找到单链表中倒数第k个节点。

这道题的考点在于我们怎么在一个单链表中找到倒数第n个元素? 由于是单链表,所以我们没办法从最后一个元素数起,然后数n个得到答案。 但这种最直观的思路显然是没错的,那我们有没有办法通过别的方式,从最后的元素数起数 n个来得到我们想要的答案呢。

这个次序颠倒的思路可以让我们联想到一种数据结构:栈。

我们如果遍历一遍单链表,将其中的元素压栈,然后再将元素一一出栈。那么, 第n个出栈的元素就是我们想要的。

那我们是不是需要显式地用栈这么一个结构来做这个问题呢?答案是否。看到栈,我们应当 要想到递归,它是一种天然使用栈的方式。所以,第一种解决方案用递归,让栈自己帮我 们从链表的最后一个元素数起。

思路很简单,如果指向链表的指针还未空,就不断递归。当指针为空时开始退递归,这个过 程n不断减1,直接等于1,即可把栈中当前的元素取出。代码如下:

node *pp;
int nn;
void findNthToLast1(node *head){
if(head==NULL) return;
findNthToLast1(head->next);
if(nn==) pp = head;
--nn;
}

虽然我们没办法从单链表的最后一个元素往前数,但如果我们维护两个指针, 它们之间的距离为k。然后,我将这两个指针同步地在这个单链表上移动,保持它们的距离 为k不变。那么,当第二个指针指到空时,第一个指针即为所求。很tricky的方法, 将这个问题很漂亮地解决了。

C++实现代码:

#include<iostream>
#include<new>
using namespace std; struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL) {}
}; void createList(ListNode *&L)
{
int arr[]= {,,,,,,,,,};
int i;
ListNode *p=NULL;
for(i=; i<; i++)
{
ListNode *tmp=new ListNode(arr[i]);
if(L==NULL)
{
L=tmp;
p=tmp;
}
else
{
p->next=tmp;
p=tmp;
}
}
} ListNode *findKNode(ListNode *L,int k)
{
if(L==NULL)
return NULL;
ListNode *p=L;
ListNode *q=L;
int count=;
while(q)
{
if(count==k)
{
p=p->next;
q=q->next;
}
else
{
count++;
q=q->next;
}
}
if(count==k)
return p;
else
return NULL;
} int main()
{
ListNode *head=NULL;
createList(head);
ListNode *p=head;
while(p)
{
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
p=findKNode(head,);
if(p)
cout<<p->val<<endl;
}

careercup-链表 2.2的更多相关文章

  1. [CareerCup] 2.1 Remove Duplicates from Unsorted List 移除无序链表中的重复项

    2.1 Write code to remove duplicates from an unsorted linked list.FOLLOW UPHow would you solve this p ...

  2. [CareerCup] 2.2 Kth to Last Element of Linked List 链表的倒数第k个元素

    2.2 Implement an algorithm to find the kth to last element of a singly linked list. 这道题让我们求链表中倒数第k个元 ...

  3. [CareerCup] 2.3 Delete Node in a Linked List 删除链表的节点

    2.3 Implement an algorithm to delete a node in the middle of a singly linked list, given only access ...

  4. [CareerCup] 2.4 Partition List 划分链表

    2.4 Write code to partition a linked list around a value x, such that all nodes less than x come bef ...

  5. [CareerCup] 2.6 Linked List Cycle 单链表中的环

    2.6 Given a circular linked list, implement an algorithm which returns the node at the beginning of ...

  6. [CareerCup] 2.7 Palindrome Linked List 回文链表

    2.7 Implement a function to check if a linked list is a palindrome. LeetCode上的原题,参见我之前的博客Palindrome ...

  7. [CareerCup] 4.4 Create List at Each Depth of Binary Tree 二叉树的各层创建链表

    4.4 Given a binary tree, design an algorithm which creates a linked list of all the nodes at each de ...

  8. [CareerCup] 17.13 BiNode 双向节点

    17.13 Consider a simple node-like data structure called BiNode, which has pointers to two other node ...

  9. 二叉树系列 - 二叉搜索树 - 线性时间内把有序链表转化为BST

    引言 本文来自于Google的一道题目: how to merge two binary search tree into balanced binary search tree. how to me ...

  10. Careercup - Google面试题 - 5735304249999360

    2014-05-03 23:18 题目链接 原题: Insert a element in a sorted circular linked list 题目:题意简单明了,向一个有序的循环单向链表中插 ...

随机推荐

  1. 几MB的大图片变成几百KB

    使用windows自带的“画图”工具就可以. 1.用“画图”打开图片. 2.点击“重新调整大小” 弹出如下窗口 修改这里的“水平”和“垂直”,如都从100改为30.改完之后,点击确定,最后再“保存”或 ...

  2. webserver<2>

    #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wai ...

  3. 四校训练 warm up 14

    A:Pythagoras's Revenge 代码: #include<cstdio> #define ll long long using namespace std; int main ...

  4. PHP传引用报错(5.4版本)

    php5.3系列版本以及以前版本,传引用没有什么问题,升级到php5.4以后,传引用的地方,全报错 Fatal error: Call-time pass-by-reference has been ...

  5. DJANGO,获取当前用户名,用户组名,用户组权限

    样例,为下一步自定义用户权限作一下代码准备: def get_context_data(self, **kwargs): if self.request.user.is_authenticated() ...

  6. go与rpc

    Go语言的RPC介绍(含Protobuf-RPC) http://www.open-open.com/lib/view/open1389251727289.html

  7. Multi-Die系统介绍

    一个典型的存储系统一般是有几片NAND存储器组成的.一般会使用8-bit的总线,用来将不同的存储器与控制器进行连接,如图2.32所示.一个系统中多片NAND的存储系统可以提高存储容量,同时还可以提高读 ...

  8. Super Phyllis(穷举+搜索)

    http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2723 题意:给出一些字符串u,v,代表u-&g ...

  9. -_-#【JS】element.click()

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  10. [PeterDLax著泛函分析习题参考解答]第3章 Hahn-Banach 定理

    1. 证明 $(10'$). 证明: $\ra$: 由 $p_K(x)<1$ 知 $$\bex \exists\ 0<a<1,\st \cfrac{x}{a}\in K. \eex$ ...