反转链表

#include<stdio.h>
#include<malloc.h>
typedef struct  LNode{
	int num;
	struct LNode * next;
}LNode,*LinkList;

LinkList linkreverse(LinkList );
LinkList reverse(LinkList);
int main(){
	LinkList a,b,c,d,head;
	head=(LinkList)malloc(sizeof(LNode));
	a=(LinkList)malloc(sizeof(LNode));
	b=(LinkList)malloc(sizeof(LNode));
	c=(LinkList)malloc(sizeof(LNode));
	d=(LinkList)malloc(sizeof(LNode));	
	a->num=1;a->next=b;
	b->num=2;b->next=c;
	c->num=3;c->next=d;
	d->num=4;d->next=NULL;
	head->next=a;

	//------print the link---------
/*	LinkList p;
	p=head->next;
	while(p){
		printf("%d ",p->num);
		p=p->next;
	}
	printf("\n");*/

	head=reverse(head);

	//------print the link---------
	LinkList p;
	p=head->next;
	while(p){
		printf("%d ",p->num);
		p=p->next;
	}
	printf("\n");

	return 0;
}

LinkList linkreverse(LinkList head){
	if(head==NULL)
		return NULL;
	LinkList pre,cur,nex;
	cur=head->next;
	pre=NULL;
	while(cur){
		nex=cur->next;
		cur->next=pre;
		pre=cur;
		cur=nex;
	}
	head->next=pre;
	return head;
}

LinkList reverse(LinkList head){
	if(head==NULL||head->next==NULL)
		return NULL;
	LinkList cur,nex;
	cur=head->next;//point to the first node
	while(cur->next!=NULL){
		nex=cur->next;
		cur->next=nex->next;
		nex->next=head->next;
		head->next=nex;
	}
	return head;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值