算法题目(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)