未知链表的求中间位置

直接上代码:

/*

设置两个指针*one、*two都指向单链表的头节点。其中* two的移动速度是*one的2倍。当* two指向末尾节点的时候,*one正好就在中间了。

*/

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

#define LEN sizeof(struct node)

struct node
{
	int date;
	struct node *next;
};

struct node *CreateList();
void TraverseList(struct node * head);
struct node *findmid(struct node *head);
struct node *findmid(struct node *head);

//
struct node *CreateList()
{
	struct node * head;//头结点
	struct node * pcurrent;//保存新创建结点的地址
	struct node * tail;//保存原链表最后一个接结点的地址
	int num=0;
	//int n=0;

	head=tail=NULL; /*开始 head and tail指向 NULL*/ 

	scanf("%d",&num);
	while(num!=0)/*只要学号不为 0,就继续录入下一个节点*/
	{
		pcurrent=(struct node *)malloc(LEN);
		pcurrent->date=num;
		pcurrent->next=NULL;
		if(head==NULL)
			head=pcurrent;
		else
			tail->next=pcurrent;
		//尾指针指向新的表尾
		tail=pcurrent;
		scanf("%d",&num);
	}
	//返回头指针 
	return head;
}

void TraverseList(struct node * head)
{
	struct node * ptr;
	if(head==NULL)
	{
		printf("No Records");
		exit(0);
	}
	else
	{
		for(ptr=head; ptr; ptr=ptr->next)
			printf("%d\n",ptr->date);
	}
}

struct node *findmid(struct node *head)
{
	struct node *one = head, *two = head;
	while(two != NULL)
	{
		two = two->next;
		if(two != NULL)
		{
			two = two->next;
			one = one->next;
		}
	}
	return one;
}

int main(void)
{
	struct node * head;//head 用来放链表头结点的地址
	struct node * mid;
	//struct node * ptr;
	
	puts("......Find middle element......\n");
	puts("Input numbers in the next line:\n");
	
	head=(struct node *)malloc(LEN);
	
	head=CreateList();
	printf("The list members are :============================\n");
	//遍历链表
	TraverseList(head);//遍历 
	
	mid = findmid(head);
	printf("mid = %d\n",mid->date);
	
	return 0;
}




posted @ 2012-07-07 20:33  wdliming  阅读(109)  评论(0编辑  收藏  举报