好程序员训练营
------我的c语言笔记,期待与您交流!
#include
#include
#include //线程锁(init锁),Linux下使用
pthread_mutex_t add_tail_lock;
typedef struct list_t{
int value;
struct list_t *next;
}node;
node *creat(); //建立单向链表
int length(node *head); //计算单链表长度
void init_add_tail_lock(); //初始化init锁
node *add(node *tail,int value); //安全的在单链表末尾添加元素,Linux下使用
int main()
{
node *head, *last_p = 0; //有时候记得要初始化指针
int value = 100;
init_add_tail_lock();
head = creat();
free_p(head);
last_p = head;
print(add(last_p, value));
print(head);
print(tail);
}
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);
}
extern pthread_mutex_t add_tail_lock;
void init_add_tail_lock()
{
pthread_mutex_init(&add_tail_lock,NULL);
}
node *add(node *tail,int value)
{
node *p;
if(tail==NULL)
{
return head;
}
p=(node *)malloc(sizeof(node));
if(p==NULL)
{
return head;
}
p->value=value;
p->next=NULL;
pthread_mutex_lock(&add_tail_lock);
while(tail->next!=NULL)
{
tail=tail->next;
}
tail->next=p;
pthread_mutex_unlock(&add_tail_lock);
return tail;
}