C语言中的经典小程序4

来源:互联网 发布:js 按钮 点击再点击 编辑:程序博客网 时间:2024/05/20 02:30

8、 给出一个单链表,不知道节点个数N,怎样只遍历一次就可以求出中间节点。

       这个问题的大体思路是:设立两个指针,比如*p和*q。p每次移动两个位置,即p = p->next->next; 

       q每次移动一个位置,即q = q->next; 当p达到最后一个节点时,q就是中间节点了。

       下面是可以实现的具体代码:

    

     #include<stdio.h>
     #include<stdlib.h>

     typedef struct Node{
        int data;
        struct Node *next;

     }node;

             /*建立单链表*/
 node *creat()
 {
 
      node *head,*p,*s;
      int x,cycle=1;
      head = (node*)malloc(sizeof(node));
      p = head;
      printf("please input the data:\n");
      while(cycle)
     {
          scanf("%d",&x);
          if(x != 0)
          {
              s = (node*)malloc(sizeof(node));
              s->data = x;
              p->next = s;
              p = s;
          }
          else
         {
             cycle = 0;
         }
    }
        p->next = NULL; //末尾节点必须指向空,否则会有灾难性后果。
        head = head->next;
 
        return head;

}

           /* 打印链表*/
void print(node *head)
{
         int n = 0;
         node *p = NULL, *q = NULL;
         p = head;
         while(p != NULL)
        {
            p = p->next;
            n++;
        }
        printf("the length of chain is %d \n",n);

        q = head;
        printf("the chain is :\n");
        while (q != NULL)
         {
            printf("%d ",q->data);
            q = q->next;
         }
        printf("\n");

}


           /*不 知道节点数N,遍历一次找到中间节点*/
void searchmid(node *head)
{
       node *q = NULL;
       node *p = NULL;
       q = head;
       p = head;
       while(p->next->next != NULL)
      {
            p = p->next->next;
            printf("p = %d\n",p->data);
            q = q->next;
           if(p->next !=NULL)
           {
             continue;
           }
          else
          {
              break;
           }
      }
      printf("the mid node is : %d\n",q->data);

}

int main(void)
{
      node *head = NULL;
      head = creat();
      print(head);
      searchmid(head);

      return 0;
}

注意:在这个程序里被涂为红色的代码,是关键性代码,你可能在《程序员面试宝典》之类的书

            上看到过这个解题思维,但是那只是思维,具体代码是不能参考的,如果代码里没有这部

            分红色代码的话,当你输入的数值个数是奇数个时执行到while(p->next->next != NULL);

            时会出现段错误。

原创粉丝点击