// list.cpp : 定義控制臺應用程序的入口點。
//
#include "stdafx.h"
#include "malloc.h"
/*************************結構體與鏈表************************/
/*************************2014年4月23日 00:51:55************************/
typedef struct node//創建鏈表要有一個指向下一個該結構體的指針-|
{ // |
int name; // |
node*next; //<<-------------------------------------------|
};
struct node*create()
{
node*p11=(node*)malloc(sizeof(node));
p11->next=NULL; //鏈表的第一個節點next必須為空,檢測用于
return p11;
};
void add(node*head,node*n1)
{
node*head1=head;
while(head1->next!=NULL)//遍歷的方式檢測每個節點的next是不是為空,為空說明是最后一個節點。
{
head1=head1->next;
}
head1->next=n1;//給最后一個鏈表的next添加新的鏈表(即n1)
}
void print(node*head)
{
node*head1=head;
while(head1->next!=NULL)
{
head1=head1->next;
printf("%d\n",head1->name);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
node*HEAD=create();
int arr[]={1,2,3};
for(int i=0;i<3;i++)
{
node*n1=(node*)malloc(sizeof(node));
n1->name=arr[i];
n1->next=NULL;
add(HEAD,n1);
}
print(HEAD);
return 0;
}
|