您的位置:首页 > 其它

一些简单的链表算法一

2012-12-27 11:14 323 查看
链表是很重要的一种数据结构,又是一种看似简单但很难熟练掌握的东西,究其主要原因应该就是它与指针结合的太紧密了。为了让大家更好的学习,特将一些简单的算法罗列如下,大家一起探讨(用c写的而且是不带头结点的)

首先是链表的结构体:

typedef struct node
{
int data;
struct node* next;
}LIST;

1、往链表中压入元素

void Push(LIST **headRef,int newData)
{
LIST *newNode = new(LIST);
newNode->data = newData;
newNode->next = *headRef;
*headRef = newNode;
}


如果我们加入的顺序是1、2、3则得到的链表是{3、2、1}

我们简单构建一个链表{1、2、3}:

LIST* BuildOneTwoThree()
{
LIST *head = 0;
Push(&head,3);
Push(&head,2);
Push(&head,1);
return head;
}


2、计算链表的长度

int Length(LIST*head)
{
LIST *current = head;
int length = 0;
while(current != 0)
{
length++;
current = current->next;
}
return length;
}


3、计算给定一个元素计算在链表中出现的次数

int Count(LIST*head,int data_to_find)
{
int count = 0;
LIST *current = head;
while(current != 0)
{
if(current->data == data_to_find)
count++;
current = current->next;
}
return count;
}


4、 给定一个索引取出那个位置的值(索引是从0开始的)

int GetNth(LIST*head,int index)
{
LIST *current = head;
assert(head != 0);
assert(index >= 0);
for(index; index > 0; index--)
{
current = current->next;
}
return current->data;
}


5、删除一个链表并释放所有内存将头指针指向NULL

void DeleteList(LIST**headRef)
{
LIST*current = *headRef;
LIST*next = 0;
for(current ; current != 0;)
{
next = current->next;
delete(current);
current = next;
}
*headRef = 0;
}


6、弹出第一个元素并删除第一个节点

int Pop(LIST**headRef)
{
int data = 0;
assert(*headRef != 0);
LIST *current = *headRef;
data = (*headRef)->data;
*headRef = (*headRef)->next;
delete(current);
return data;

}


7、在给定索引处插入元素

void InsertNth(LIST**headRef,int index,int newData)
{
if(index == 0)
{
Push(headRef,newData);
}
else
{
LIST*current = *headRef;
for(index; index > 1; index--)
{
assert(current != NULL);
current = current->next;
}
assert(current != 0);
Push(¤t->next,newData);
}
}


  上面的都是一些关于链表简单的算法,有些是参考斯坦福大学的讲义而来的,特此说明

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: