每天一道算法题7 查找链表中倒数第k个结点 ; 输入一个单向链表。如果该链表的结点数为奇数,输出中间的结点;如果链表结点数为偶数,输出中间两个结点前面的一个

typedef struct list_node{
  int i;
  list_node *next;
}LIST_NODE;

LIST_NODE *find_node(LIST_NODE *head, int k)
{
  LIST_NODE *p1 = head;
  int count = 0;
  while(p1 && count++ < k)
    p1 = p1->next;
  if (!p1)
  {
    return NULL;
  }
  LIST_NODE *p2 = head;
  while(p1 && p1->next)
  {
    p1 = p1->next;
    p2 = p2->next;
  }
  return p2;
}

LIST_NODE *find_node(LIST_NODE *head)
{
  LIST_NODE *p1, *p2;
  if (head == NULL || head->next == NULL)
  {
    return head;
  }
  p1 = head;
  p2 = head->next;
  while(p2->next && p2->next->next)
  {
    p2 = p2->next->next;
    p1 = p1->next;
  }
  if (p2->next)
  {
    return p1->next;
  }
  return p1;
}

int _tmain(int argc, _TCHAR* argv[])
{
  LIST_NODE *head = new LIST_NODE;
  head->i = 0;
  LIST_NODE *temp = head;
  for (int j = 0; j < 11; j++)
  {
    LIST_NODE *p = new LIST_NODE;
    p->i = ++j;
    temp->next = p;
    temp = p;
  }
  temp->next = NULL;

  for (LIST_NODE *temp = head; temp; temp = temp->next)
  {
    cout << " " << temp->i << " ";
  }
  LIST_NODE *temp2 = find_node(head);
  if(temp2)
    cout << "/n" << temp2->i << endl;

  system("pause");
    return 0;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值