好程序員訓練營
<A href="http://www.goodprogrammer.org/" target="blank">ios培訓</A>
------我的c語言筆記,期待與您交流!
#include<stdio.h>
#include<stdlib.h>
typedef struct list_t{
int value;
struct list_t *next;
}node;
node *creat(); //建立單向鏈表
int length(node *head); //計算單鏈表長度
node *insert(node *head,int num); //單鏈表插入
void print(node *head); //打印單鏈表
int main()
{
node *head; //有時候記得要初始化指針
int value = 100;
head = creat();
print(head);
printf("\n");
}
node *creat()
{
node *head, *p, *s;
int x, cycle = 1;
head = (node*)malloc(sizeof(node));
p = head;
while (cycle)
{
printf("please input the data : ");
scanf_s("%d\n", &x);
if (x != 0) //鏈表以0結尾
{
s = (node*)malloc(sizeof(node));
s->value = x;
printf("%d\n", s->value);
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);
}
node *insert(node *head, int num)
{
node *p0, *p1, *p2=0;
p1 = head;
p0 = (node *)malloc(sizeof(node));
p0->value = num;
while ( p0->value <= p1->value && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (p0->value > p1->value)
{
if (head == p1)
{
p0->next = p1;
head = p0;
} else{
p2->next = p0;
p0->next = p1;
}
}
else
{
p1->next = p0;
p0->next = NULL;
}
return head;
}
void print(node *head)
{
node *p;
p = head;
while (p != NULL)
{
printf("%d", p->value);
p = p->next;
}
}