首页 > 代码库 > 单链表练习
单链表练习
//code:
#include
#include
using namespace std;
typedef int status;
typedef int elemType;
typedef struct lNode
{
elemType num;
struct lNode *next;
}lNode,*linkNode;
linkNode initListNode();
void echNode(linkNode L);
linkNode insertNode(linkNode L);
void creatList(linkNode L,int n);
void echList(linkNode L);
linkNode delNode(linkNode L,int n);
linkNode searchNode(linkNode head,int n);
int main()
{
linkNode l,m;
l=initListNode();
printf("After Initialization:\n");
echNode(l);
printf("\nCreat and echo List:\n");
creatList(l,4);
echList(l);
printf("\nFind 2nd elemet:\n");
m=searchNode(l,2);
printf("Find result:\n");
echNode(m);
printf("\nDelt nodes and echo List\n");
m=delNode(l,1);
m=delNode(m,1);
echList(m);
}
linkNode initListNode()
{
linkNode L;
L=(linkNode)malloc(sizeof(lNode));
L->num=0;
L->next=NULL;
return L;
}
void creatList(linkNode L,int n)
{
int i;
for(i=0;i
{
L=insertNode(L);
L->num=i+1;//num value
}
}
void echNode(linkNode L)
{
printf("Node num is %d\n",L->num);
}
linkNode insertNode(linkNode L)
{
linkNode tmpp;
tmpp=(linkNode)malloc(sizeof(lNode));
//tmpp->num=9;
tmpp->next=NULL;
L->next=tmpp;
return tmpp;
}
void echList(linkNode L)
{
linkNode tmpp;
tmpp=L;
do
{
echNode(tmpp);
tmpp=tmpp->next;
}
while(tmpp);
}
linkNode searchNode(linkNode head,int n)
{
linkNode tmpp;
tmpp=head;
//printf("\nSearch %dnd element!!\n",n);
while(--n)
{
if(tmpp->next)
{
tmpp=tmpp->next;
}
else
{
//cout<<"Over max quantity of Nodes of the List";
exit(0) ;
}
}
//printf("The num is %d.\n\n",tmpp->num);
return tmpp;
}
linkNode delNode(linkNode head,int n)
{
linkNode tmpp,nodep;
if(n>1)
{
tmpp=searchNode(head,n-1);
nodep=tmpp->next;
tmpp->next=tmpp->next->next;
free(nodep);
return head;
}
else if(n=1)
{
tmpp=head->next;
free(head);
return tmpp;
}
}
result:
After Initialization:
Node num is 0
Creat and echo List:
Node num is 0
Node num is 1
Node num is 2
Node num is 3
Find 2nd elemet:
Find result:
Node num is 1
Delt nodes and echo List
Node num is 2
Node num is 3
请按任意键继续. . .
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。