常见小算法的实现
- 概述
- 最近时间开始空余,所以,就抽时间复习一下算法和数据结构,顺便实现一些小的常用算法.
- 如果大家有更好的实现方法,可以尽情留言.
- Dev-C++ 4.9.9.2
- window XP
(1) 怎样把一个链表掉个顺序(也就是反序,注意链表的边界条件并考虑空链表)?(不知道那一年微软的一道笔试题)
(a)创建链表.
- 分析:这个问题的核心解决步骤共分为三部分:
(b)逆转链表:判断链表是否为空;如果链表节点多余一个时,对链表进行逆转操作.(具体为什么,不说大家也清楚,是吧?)
(c)输出逆转后的链表中的元素值,以验证.
实现代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct listNode
{
struct listNode *link;
int data;
}*node;
//creat a new node
node getNode(node newNode,int val )
{
if(!newNode)
exit(0);
newNode->link=NULL;
newNode->data=val;
return newNode;
}
// insert a new node into the linklist
int insertNode(node prev,node newNode)
{
if(!newNode) return 0;
newNode->link=prev->link;
prev->link=newNode;
return 1;
}
void buildList(node head)
{
int value;
node newNode=(node)malloc(sizeof(node));
node p=head;
scanf("%d",&value);
// input the value of node in the new linklist
while(value!=-1)
{
newNode=getNode(newNode,value);
insertNode(p,newNode);
p=p->link;//p link to the last node
scanf("%d",&value);
newNode=(node)malloc(sizeof(node));
}
}
//reverse the linkList
void reverseList(node head)
{
node p=head->link;
node q=p->link;
node temp;
// check the linkList is empty
if(p==NULL)
{
printf("The list is empty!\n");
}
p->link=NULL;
while(q!=NULL)
{
temp=q->link;
q->link=p;
p=q;
q=temp;
}
head->link=p;
}
// print the value of node in the reversed linkList
void print(node head)
{
node p=head->link;
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->link;
}
system("pause");
}
int main(void)
{
node head=(node)malloc(sizeof(node));
head=getNode(head,0);
buildList(head);
print(head);
reverseList(head);
print(head);
}
posted on 2009-10-08 17:42 Creative Common 阅读(252) 评论(0) 编辑 收藏 举报