您的位置:首页 > 编程语言 > C语言/C++

带表头的单向链表实现(C语言)

2010-01-30 13:55 495 查看
带表头的单向链表实现(C语言)在vs 2008上测试编译并成功执行

头文件linkedlist.h

#ifndef _LINKEDLIST_H
#define _LINKEDLIST_H
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *next;
}Node, *PNode;

PNode create();
void addElement(PNode head, DataType data);
void removeElement(PNode head, int index);
DataType elementAt(PNode head, int index);
void show(PNode head);
void insert(PNode head, int index, DataType data);
void removeAll(PNode head);
void destroy(PNode head);
#endif


源文件LinkedList.cpp

#include <stdio.h>
#include <stdlib.h>
#include "linkedlist.h"

//create a new node
PNode create()
{
PNode node = (PNode)malloc(sizeof(Node));
if(NULL == node)
{
printf("Allocate memory failed.");
return NULL;
}
node->next = NULL;
return node;
}

//add a new element to the first position of the list
void addElement(PNode head, DataType data)
{
PNode node = create();

if(NULL != node)
{
node->data = data;
node->next = head->next;
head->next = node;
printf("Add element /"%d/" successfully./n", data);
}
else
printf("Add element failed./n");
}

//display all the elements in the list
void show(PNode head)
{
PNode p = head->next;
while(NULL != p)
{
printf("%d ", p->data);
p = p->next;
}
}

//remove all elements
void removeAll(PNode head)
{
PNode p = head->next;
while(NULL != p)
{
head->next = p->next;
free(p);
p = head->next;
}
printf("All elements are removed./n");
}

//destroy the list
void destroy(PNode head)
{
PNode p = head->next;
while(NULL != p)
{
head->next = p->next;
free(p);
p = head->next;
}
free(head);
printf("Destoryed the list./n");
}

//remove the element at index
void removeElement(PNode head, int index)
{
PNode p = head;
PNode q = head->next;

int count = 1;
while(NULL != q)
{
if(index == count)
{
p->next = q->next;
free(q);
q = p->next;
printf("Element removed./n");
break;
}
p = q;
q = q->next;
count++;
}

}

//get element at index
DataType elementAt(PNode head, int index)
{
PNode p = head->next;
int count = 1;

while(NULL != p)
{
if(index == count)
return p->data;
p = p->next;
count++;
}
return -1;
}

void insert(PNode head, int index, DataType data)
{
PNode p = head;
int count = 1;

while(NULL != p)
{
if(index == count)
{
PNode node = create();
node->data = data;
node->next = p->next;
p->next = node;
printf("Element /"%d/" successfully inserted into the list at %d./n",data, index);
break;
}
p = p->next;
count++;
}
}

int main()
{
PNode head = create();

addElement(head, 1);
addElement(head, 2);
show(head);
printf("/n");
insert(head, 2, 3);
show(head);
printf("/n");
printf("The need element is:%d/n",elementAt(head,2));
removeElement(head, 2);
show(head);
printf("/n");
destroy(head);
return 0;
}


运行结果:

Add element "1" successfully.
Add element "2" successfully.
2 1
Element "3" successfully inserted into the list at 2.
2 3 1
The need element is:3
Element removed.
2 1
Destoryed the list.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: