C 链表的反转(数据结构与算法)

建立一个链表,然后将其中的元素进行反转。

#include<stdio.h>
#include<stdlib.h>

struct Node
{
	int data;
	struct Node *next;
};

void display_link(struct Node *head)
{	
	struct Node *p;
	for(p = head; p != NULL; p = p->next) {
		printf("%4d",p->data);
	}
	printf("\n");
}

struct Node * new_link()
{
	struct Node *head = NULL, *p1 = NULL ,*p2 = NULL;
	int data;
	int i = 1;
	printf("enter the data:\n");
	p1 = (struct Node * )malloc(sizeof(struct Node));
	while(1) {
		scanf("%d",&p1->data);
		if(head == NULL) {
			head = p1;
		}
		p2 = p1;
		if(i == 10) {
			break;
		}
		p1 = (struct Node*)malloc(sizeof(struct Node));
		p2->next = p1;
		i++;
	}
	p2->next = NULL;
	
	return head;
}

struct Node *transvert_link(struct Node *head)
{
	struct Node *p,*p2,*p3;
	
	p = head;
	p2 = head->next;
	p3 = head->next->next;
	while(p3 != NULL) {
		p2->next = p;
		p = p2;
		p2 = p3;
		p3 = p3->next;
	}
	p2->next = p;
	head->next = NULL;

	return p2;
}

int main(void)
{
	struct Node *head;
	
	head = new_link();
	printf("\n the data before transvert is:\n");
	display_link(head);
	head = transvert_link(head);
	printf("\n the data after transvert is:\n");
	display_link(head);
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值