码迷,mamicode.com
首页 > 其他好文 > 详细

Singly Linked List

时间:2016-10-19 20:23:32      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

Singly Linked List

Singly linked list storage structure:
typedef struct Node
{
ElemType data;
struct Node *next;
}Node;


typedef struct Node *LinkList;

LinkedList without head node:


LinkedList with head node:

Operations:

/*check the size of link list.*/
int ListLength(LinkList *L)
{
i=0;
LinkList p;
p=L->next;
while(!p)
{
p=p->next;
++i;
}
return i;
}

/*return the value of number i data element in list L to e.*/
Status GetElem(LinkList L,int i,ElemType *e)
{
int j;
LinkList p;
/*let p point to the first node of L.*/
p=L->next;
/*j works as a counter.*/
j=1;
/*p is a null and j is not equal to i.*/
while(p&&j<i)
{
/*let p point to the next node.*/
p=p->next;
++j;
}
/*the ith element does not exist.*/
if(!p||j>i)
{
return ERROR;
}
/*get the number i element.*/
*e=p->data;
return OK;
}

List Insert


Status ListInsert(LinkList *L,int i,ElemType e)
{
int j;
LinkList p,s;
p=*L;
j=1;
/*search for number i node.*/
while(p&&j<i)
{
p=p->next;
++j;
}
if(!p||j>i)
{
/*number i node does not exist.*/
return ERROR;
}
/*make a new node.*/
s=(LinkList)malloc(sizeof(Node));
s->data=e;
/*key steps:*/
s->next=p->next;
p->next=s;
return OK;

}

List Delete


Status ListDelete(LinkList *L,int i,ElemType *e)
{
int j;
LinkList p,q;
p=*L;
j=1;
/*search for number i node.*/
while(p->next&&j<i)
{
p=p->next;
++j;
}
if(!(p->next)||j>i)
{
/*number i node does not exist.*/
return ERROR;
}
/*key steps*/
q=p->next;
p->next=q->next;
*e=q->data;
free(q);
return OK;

}

/*create a list using head inserting method.*/
void CreateListHead(LinkList *L,int n)
{
LinkList p;
int i;
*L=(LinkList)malloc(sizeof(Node));
/*create a linked list with head node.*/
(*L)->next=NULL;
for(i=0;i<n;i++)
{
/*generate a new node.*/
p=(LinkList)malloc(sizeof(Node));
/*store the data of number i node as 100+i.*/
p->data=100+i;
p->next=(*L)->next;
/*insert the node to head.*/
(*L)->next=p;
}
}


/*create a list using tail inserting method.*/
void CreateListTail(LinkList *L,int n)
{
LinkList p,r;
int i;
/*create a linked list with head node.*/
*L=(LinkList)malloc(sizeof(Node));
r=*L;
for(i=0;i<n;i++)
{
/*generate a new node.*/
p=(LinkList)malloc(sizeof(Node));
p->data=100+i;
r->next=p;
r=p;
}
/*marks the end of list.*/
r->next=NULL;
}

/*clear the list to empty.*/
Status ClearList(LinkList *L)
{
LinkList p,q;
/*let p point to first node.*/
p=(*L)->next;
/*while it‘s not list end.*/
while(p)
{
q=p->next;
free(p);
p=q;
}
/*set the list head pointer to null.*/
(*L)->next=NULL;
return OK;
}

Singly Linked List

标签:

原文地址:http://www.cnblogs.com/mitnick/p/5978400.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!