单行链表寻找倒数第k个节点



单行链表寻找倒数第k个节点,

/**
*题目介绍:给出一个单向链表,输出该链表的倒数第k个节点
*           设尾节点开始从0编号
*/

解题思路:两个指针往后移动,一定要注意边界的处理情况。此处我设置了一个头指针,头指针不存数据,仅仅作为头标志。

 

 

[cpp] view plaincopy

  1. /**
  2. *题目介绍:给出一个单向链表,输出该链表的倒数第k个节点
  3. *           设尾节点开始从0编号
  4. */
  5. #include <iostream>
  6. #include <stdlib.h>
  7. #include <cstdio>
  8. using namespace std;
  9. struct node
  10. {
  11.     int value;
  12.     struct node * next;
  13. } *head;
  14. inline void nodeinit(struct node *n)
  15. {
  16.     n->next = NULL;
  17.     n->value = 0;
  18. }
  19. void creatnodelist()
  20. {
  21.     //头指针 应该首先分配地址
  22.     if(head == NULL)
  23.         head = (struct node *)malloc(sizeof(struct node));
  24.     nodeinit(head);
  25.     int v;
  26.     struct node * pt = head;
  27.     scanf(“%d”,&v);
  28.     while(v)
  29.     {
  30.         if(pt->next == NULL)
  31.             pt->next = (struct node *)malloc(sizeof(struct node));
  32.         pt=pt->next;
  33.         nodeinit(pt);
  34.         pt->value = v;
  35.         //cout<<pt->value ;
  36.         scanf(“%d”,&v);
  37.     }
  38. }
  39. int findLastK(int k)
  40. {
  41.     struct node * p1=head;
  42.     struct node * p2=head;
  43.     while(k–)
  44.         p1=p1->next;
  45.     p1=p1->next;
  46.     while(p1 != NULL)
  47.         p1=p1->next,p2=p2->next;
  48.     return p2->value;
  49. }
  50. void print()
  51. {
  52.     struct node * p=head->next;
  53.     while(p!=NULL)
  54.         cout<<p->value<<”  ”,p=p->next;
  55. }
  56. int main()
  57. {
  58.     cout << ”create node list:” << endl;
  59.     creatnodelist();
  60.     print();
  61.     int k;
  62.     cout<<”\ninput k :”;
  63.     scanf(“%d”,&k);
  64.     cout<<”\nthe last ”<<k<<” node is : ”<<findLastK(k)<<endl;
  65.     return 0;
  66. }