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

c语言之链表实现

2013-03-13 22:12 239 查看
1 #include <stdio.h>
#include <stdlib.h>

struct Node
{
struct Node *next;
int num;
};

struct Node *list = NULL;

/**
* 初始化链表
*/
void initList()
{
list = (struct Node *)malloc(sizeof(struct Node));
list->next = NULL;
}

/**
*添加链表元素
*/
void addList(int i)
{
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
p->num = i;
p->next = list;
list = p;
}

/**
*打印链表内容
*/
void printfList()
{
int i =0;
struct Node *p = list;
while(p->next !=NULL)
{
i++;
printf("num = %d\n",p->num);
p = p->next;
}
}

/**
* 获得链表长度
*/
int getListLength()
{
int length = 0;
struct Node *node = list;
while(node->next != NULL)
{
length++;
node = node->next;
}

return length;
}

/**
*插入数据到链表
*/
int insertToList(int position ,int num)
{
int length = getListLength();

if(position >length-1)
{
return -1;
}

if(position == length-1)
{
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
node->num  = num;
node->next = list;
list = node;
return 0;
}
else
{
/*        int i=0;

struct Node *node = list;
while(i<position)
{
node = node->next;
}

struct Node *p = (struct Node *)malloc(sizeof(struct Node));
p->num = num;
p->next = node->next;
node->next = p;
*/
return 0;
}

}

/**
*逆序链表
*/
void inversionToList()
{
struct Node *p,*q,*front;
p = list;

while(p!=NULL)
{
q = p->next;
p->next = front;
front = p;
p =q;
}

list = p;
}

/**
*查找给定的元素
*/
int findListData(int key)
{
struct Node *node = list;
int i = 0;
while(node->next !=NULL)
{

if(node->num == key)
{
goto find;
}
node = node->next;
i++;
}
find:
return i;
}

int main()
{
initList();

int i = 0;
for(i = 0;i<6;i++)
{
addList(i);
}

printf("list length = %d\n",getListLength());

printf("find position = %d\n",findListData(2));

if(-1 == insertToList(2,19))
{
printf("error\n");
}

printfList();
inversionToList();

}
以上主要完成了链表的基本操作,还需要将链表的插入稍作修改
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: