C语言实现链表的原地置逆

思路

将原来的链表用头插法重新插入头节点后面

#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(SNODE)

typedef struct node
{
	int num;
	struct node *next;
}SNODE;

void print(SNODE *head)
{
	head=head->next;
	while(head!=NULL)
	{
		printf("%d ",head->num);
		head=head->next;
	}

	putchar('
');
}//print

void creatLink(int n,SNODE *head)
{
	SNODE *p,*q;
	p=head;
	while(p->next!=NULL) p=p->next;
	
	q=(SNODE*)malloc(LEN);
	q->num=n;
	q->next=NULL;

	p->next=q;

}//creatLink

void inverseLink(SNODE *head)
{
	SNODE *p,*q;
	if(head->next!=NULL)//链表不空
	{
		p=head->next;
		q=p;
		head->next=NULL;

		while(p!=NULL)//头插法重新插入
		{
			q=p->next;
			p->next=head->next;
			head->next=p;
			p=q;
		}
	}
}//inverseLink

int main()
{
	SNODE *head;
	head=(SNODE*)malloc(LEN);//新建头节点
	head->next=NULL;
	head->num=-1;
	int n;
	char c;
	while(1)//输入的整形以空格隔开
	{
		scanf("%d",&n);//读入数字
		creatLink(n,head);//插入链表
		c=getchar();//吃掉空格
		if(c=='
') break;
	}
	print(head);//打印原链表
	inverseLink(head);//置逆链表
	print(head);//打印置逆后的链表
	return 0;
}//main
原文地址:https://www.cnblogs.com/DismalSnail/p/10543916.html