程序员面试问题(五)

算法题目(2)


2.链表逆序
啥也不说,上图

下面是灼爷写的代码:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100000
struct Node{
	int element;
	struct Node* next;
};
typedef struct Node *PtrToNode;
typedef	PtrToNode Position;
typedef PtrToNode List;
void MakeEmpty(List l)
{
	l->next =NULL;
}
// insert after the head
List Insert(int x,List l)
{
	Position tmpCell;
	tmpCell =(Position)malloc(sizeof(struct Node));
	if(tmpCell ==NULL)
    {
        printf("out of space ");
        return NULL;
    }
    else
    {
		tmpCell->element = x;
		tmpCell->next =l->next;
		l->next =tmpCell;
		return l;
	}

}
void clear(List l)
{
    Position tmpCell = l->next;
    while(tmpCell != NULL)
    {
        l->next = tmpCell->next;
        free(tmpCell);
        tmpCell = l->next;
    }
}
void print(List l)
{
	Position k =l->next;
	while(k)
	{
		printf("%d\t",k->element);
		k = k->next;
	}
}
List reserve(List l)
{
	if(!l->next)
	{
		printf("an empty list");
		return NULL;
	}
	else
	{
		Position preNode,curNode,nextNode;
		preNode =NULL;
		curNode =l->next;
		nextNode =curNode->next;
		while(nextNode !=NULL)
		{
			curNode->next =preNode;
			preNode =curNode;
			curNode =nextNode;
			nextNode =nextNode->next;
		}
		curNode->next =preNode;
		l->next =curNode;
		return l;
	}
}
int main()
{
    int n;
    int arr[MAX];
    while(scanf("%d",&n)!=EOF)
    {
        List l = (List)malloc(sizeof(struct Node));
        MakeEmpty(l);
        for(int i = 0;i < n;++i)
        {
            int tmp;
            scanf("%d",&tmp);
            Insert(tmp,l);
        }
        print (l);
        printf("\n");
        reserve(l);
        print(l);
        printf("\n");
        clear(l);   //malloc的内存要记得释放
    }
	return 0;
}

时间复杂度:O(N)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值