返回单链表中倒数第N个元素问题
2013-09-14 22:25
429 查看
13.
题目:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。
链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
思路:维护两个指针,使 它们之间的距离为n。让这两个指针同步地在这个单链表上移动,保持它们的距离 为n不变。当第二个指针指到空时,第一个指针即为所求。
题目:输入一个单向链表,输出该链表中倒数第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; }
相关文章推荐
- LinkLists 链表中返回倒数第n个元素 @CareerCup
- Remove Nth Node From End of List 链表删除倒数第N个元素@LeetCode
- 《算法之美》の链表问题の获得链表中倒数第m个元素
- 单链表查找倒数第N个元素&输出中间元素
- 《算法之美》の链表问题の获得链表中倒数第m个元素
- 2.2 实现一个算法从一个单链表中返回倒数第n个元素
- 删除链表倒数第n个元素
- 返回链表中的倒数第N个节点
- 删除链表的倒数第n个元素
- Chapter 2 | Linked Lists--返回单链表倒数第n个元素及删除中间的某个节点
- 返回线性链表的倒数第n个元素
- 链表中倒数第N个元素——剑指Offer
- 移除链表倒数第n个元素
- 数据结构链表 -- 查找倒数第N个元素、中间元素、创建链表
- 找出链表倒数第n个节点元素的二个方法
- 查找单向链表倒数第n个元素
- 坚持坚持!用Java写出删除一个链表的倒数第N个节点,并返回头节点(N总是可达的)
- 删除链表中倒数第n个元素
- LeetCode[19]Remove Nth Node From End of List 删除链表倒数第n个元素
- 求链表倒数第n个元素