您的位置:首页 > 其它

返回单链表中倒数第N个元素问题

2013-09-14 22:25 429 查看
13.

题目:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。

链表结点定义如下:

struct ListNode

{

int m_nKey;

ListNode* m_pNext;

};

思路:维护两个指针,使 它们之间的距离为n。让这两个指针同步地在这个单链表上移动,保持它们的距离 为n不变。当第二个指针指到空时,第一个指针即为所求。

#include <iostream>
#include <stdio.h>
#include <cstdlib>
using namespace std;
struct ListNode
{
char data;
ListNode* next;
};
ListNode* head,*p,*q;
ListNode *pone,*ptwo;

ListNode* fun(ListNode *head,int k)
{
pone = ptwo = head;
for(int i=0;i<=k-1;i++)
{

ptwo=ptwo->next;
cout << pone->data << "..." << ptwo->data << endl;
}

while(ptwo != NULL)
{
cout << "!!" << ptwo->data << endl;
pone=pone->next;
ptwo=ptwo->next;
}
return pone;
}

int main()
{
char c;
head = (ListNode*)malloc(sizeof(ListNode));
head->next = NULL;
p = head;
while(c !='0')
{
q = (ListNode*)malloc(sizeof(ListNode));
q->data = c;
q->next = NULL;
p->next = q;
p = p->next;
c = getchar();
}
cout<<"---------------"<<endl;
cout<<fun(head->next->next,2)->data<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: