2链表头插法尾插法

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//尾插法
/#include<stdio.h>
#include<stdlib.h>
struct londe
{
int x;
struct londe
next;
};
#define SIZE sizeof(struct londe)
int main(void)
{
int sum = 0;
char t;
struct londe* p1 = NULL, * p2 = NULL, * head = NULL;
p1 = (struct londe*)malloc(SIZE);
if (p1 == NULL)
{
printf(“error\n”);
return -1;
}
p1->next = NULL;
scanf_s("%d", &(p1).x);
t=getchar();
head = p1;
while (p1->x != 0)
{
sum++;
p2 = p1;
p1 = (struct londe
)malloc(SIZE);
if (p1 == NULL)
return 0;
p2->next = p1;
scanf_s("%d", &p1->x);
t=getchar();
}
p2->next = NULL;
p1 = head;
printf(“sum=%d\n”, sum);
while (1)
{
printf("%d ", (*p1).x);
if (p1->next == NULL)
{
break;
}
p1=p1->next;
}
return 0;

}
*/

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//头插法
#include<stdio.h>
#include<stdlib.h>
struct londe
{
int x;
struct londe* next;
};
#define SIZE sizeof(struct londe)
int main(void)
{
int sum = 0;
char t;
struct londe* p1 = NULL, * p2 = NULL, * head = NULL;
p1 = (struct londe*)malloc(SIZE);
if (p1 == NULL)
{
printf(“error\n”);
return -1;
}
p1->next = NULL;
scanf_s("%d", &(*p1).x);
t=getchar();
head= p2 = p1;
head->next = NULL;
while (p1->x != 0)
{
sum++;

	p1 = (struct londe*)malloc(SIZE);
	if (p1 == NULL)
		return 0;
	scanf_s("%d", &p1->x);
	if (sum == 1)
	{
		p1->next =head;
		head = p1;
		p2 = p1;
	}
	else if(p1->x!=0)
	{  
		p1->next = p2;
		head = p1;
		p2 = p1;
	}
	t=getchar();
}
printf("sum=%d\n", sum);
p1 = head;
while (1)
{
	
	printf("%d ", (*p1).x);
	if (p1->next == NULL)
		break;
	p1 = p1->next;
	
}
return 0;

}

发布了26 篇原创文章 · 获赞 0 · 访问量 97

猜你喜欢

转载自blog.csdn.net/qq_45812941/article/details/104413102