7就地逆置单链表

#include<stdio.h>
#include<stdlib.h>
struct linklist {
	int data;
	struct linlist* next;
};
#define SIZE sizeof(struct linklist)
int main(void)
{
	int n;
	struct linklist* head,*p1,*p2,*p3;
	head = (struct linklist*)malloc(SIZE);
	scanf_s("%d", &n);
	getchar();
	p2 = head;
	while (n--)
	{
		p1 = (struct linklist*)malloc(SIZE);
		scanf_s("%d", &p1->data);
		getchar();
		p2->next = p1;
		p2 = p1;
	}
	p2->next = NULL;
	/////////////////////////////////////////////////////////////////////
	//输出测试
	p1 = head;
	while (p1->next)
	{
		p1 = p1->next;
		printf("%d ", p1->data);
	}
	printf("\n");
	/////////////////////////////////////////////////////////////////////
	//就地逆置单链表
	p1 = head->next;
	p2 = p1->next;
	p1->next = NULL;
	while (1)
	{
		head->next = p2;
		if (p2->next == NULL)
		{
			p2->next = p1;
			break;
		}
		p3 = p2;
		p2 = p2->next;
		p3->next = p1;
		p1 = p3;
	}
	//逆置结束
	/////////////////////////////////////////////////////////////////////
	//输出测试
	p1 = head;
	while (p1->next)
	{
		p1 = p1->next;
		printf("%d ", p1->data);
	}
	printf("\n");
	/////////////////////////////////////////////////////////////////////
	return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#include<stdio.h>
#include<stdlib.h>
struct linklist {
	int data;
	struct linlist* next;
};
#define SIZE sizeof(struct linklist)
int main(void)
{
	int n;
	struct linklist* head,*p1,*p2,*p3;
	head = (struct linklist*)malloc(SIZE);
	scanf_s("%d", &n);
	getchar();
	p2 = head;
	while (n--)
	{
		p1 = (struct linklist*)malloc(SIZE);
		scanf_s("%d", &p1->data);
		getchar();
		p2->next = p1;
		p2 = p1;
	}
	p2->next = NULL;
	/////////////////////////////////////////////////////////////////////
	//输出测试
	p1 = head;
	while (p1->next)
	{
		p1 = p1->next;
		printf("%d ", p1->data);
	}
	printf("\n");
	/////////////////////////////////////////////////////////////////////
	//就地逆置单链表
	p1 = head->next;
	p2 = p1->next;
	p1->next = NULL;
	while (p2)
	{
		p1 = p2->next;
		p2->next = head->next;
		head->next = p2;
		p2 = p1;
	}
	//逆置结束
	/////////////////////////////////////////////////////////////////////
	//输出测试
	p1 = head;
	while (p1->next)
	{
		p1 = p1->next;
		printf("%d ", p1->data);
	}
	printf("\n");
	/////////////////////////////////////////////////////////////////////
	return 0;
}
发布了26 篇原创文章 · 获赞 0 · 访问量 90

猜你喜欢

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