您的位置:首页 > 编程语言 > C语言/C++

C语言中的经典小程序4

2013-09-08 17:19 260 查看
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);

时会出现段错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: