JSMS15-逆向输出单链表剑指Offer05

176 阅读1分钟

逆向输出单链表

分析:刚开始我想的是逆置单链表,逆置之后遍历一遍就可以输出单链表了。时间复杂度为O(n),后来看了解析,是用栈来存单链表数据然后出栈。也就是常用的牺牲空间换取效率

解法1、利用递归(栈)

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


typedef struct d{
	int data;
	struct d *next;
}node;

node *create(int *a,int len)
{
	node *head=(node *)malloc(sizeof(node));
	head->data=NULL;
	node *ret=head;
	for(int i=0;i<len;i++)
	{
		
		node *s=(node *)malloc(sizeof(node));
		head->next=s;
		s->data=a[i];
		s->next=NULL;
		head=s;
	} 
	return ret;
}
void printNode(node *s)
{
	if(s!=NULL)
	{
		if(s->next!=NULL)
		{
			printNode(s->next);
		} 
		printf("%d->",s->data);
	}
}
int main()
{
	int a[]={1,2,3,4,5,6,7,8,9};
	int len=sizeof(a)/sizeof(a[0]);
	node *s=create(a,len);
	print(s);
	printNode(s);
}

解法2、逆置带头结点的单链表

    node* NIZHI(node *s)
{
	node *p,*ret,*mid,*q;
	p=s->next;
	mid=p->next;
	ret=s;
	for(;q!=NULL;)
	{
		q=mid->next;
		mid->next=p;
		p=mid;
		mid=q;
	}
	ret->next->next=q;//这里q为NULL
	ret->next=p;
	return ret; 
}