單鏈表之建立/測長/打印

題:編程實現一個單鏈表的建立/測長/打印。【日本某著名家電/通信/IT企業面試題】

答案:完整代碼如下:

// P167_example1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>

typedef struct student
{
	int data;
	struct student *next;
}node;

//建立單鏈表
node* create()
{
	node *head,*p,*s;
	int x, cycle = 1;
	head = (node *)malloc(sizeof(node));
	p = head;
	while(cycle)
	{
		std::cout<<"please input the data: ";
		std::cin>>x;
		std::cout<<std::endl;
		if(x != 0)
		{
			s = (node *)malloc(sizeof(node));
			s->data = x;
			p->next = s;
			p = s;
		}
		else
			cycle = 0;
	}
	head = head->next;
	p->next = NULL;
	return head;
}
//單鏈表測長
int length(node *head)
{
	int n = 0;
	node *p;
	p = head;
	while(p != NULL)
	{
		p = p->next;
		n++;
	}
	return n;
}
//單鏈表打印
void print(node *head)
{
	node *p;
	int n;
	n = length(head);
	std::cout<<"Now, These "<<n<<" records are: "<<std::endl;
	p = head;
	if(p != NULL)
	{
		while(p != NULL)
		{
			std::cout<<p->data<<" -> ";
			p = p->next;
		}
		std::cout<<std::endl;
	}
}


int _tmain(int argc, _TCHAR* argv[])
{
	node *head;
	head = create();
	print(head);
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章