13.
题目:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。
链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
题目:输入一个单向链表,输出该链表中倒数第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;
}