查找链表中间节点

我们可以弄两个指针都指向头节点,然后一个指针每次走一步,另一个每次走两步。

#include<stdio.h>
typedef struct link
{
  int a;
  struct link *next;
}link_t;
void main()
{
  link_t A = {1,NULL};
  link_t B = {2,NULL};
  link_t C = {3,NULL};
  link_t D = {4,NULL};
  link_t E = {5,NULL};
  A.next = &B;
  B.next = &C;
  C.next = &D;
  D.next = &E;
  link_t *h = &A;
  while(h != NULL)
  {
    printf(" %d",h -> a);
    h = h -> next;
  }
  puts("");
  puts("/////////////////////////");
  link_t *p1,*p2;
  p1 = p2 = &A; 
  while(p2 -> next != NULL && p2 -> next -> next != NULL)//这里要注意一下,p2 -> next != NULL是为了处理单数时,指针别指出去
  {
    p2 = p2 -> next -> next;
    p1 = p1 -> next;
  }
  printf("%d\n",p1 -> a);
}

 

posted @ 2016-12-18 12:42  亮哥vvv  阅读(403)  评论(0编辑  收藏  举报