C语言(7) - 数据结构之单向链表
/*
beango
2009-6-10
*/
#include <stdio.h>
typedef struct _Node
{
int data;
struct _Node* next;
}Node;
typedef struct _List
{
Node* head;
}List;
List list;
//增加节点到链表的最未端
void Insert(Node* node)
{
Node* _head = list.head;
if (_head==NULL)
{list.head = node;node->next = NULL;}
else
{
Node* _node = _head;
while (_node->next!=NULL)
_node = _node->next;
_node->next = node;
node->next = NULL;
}
}
//获取索引处的元素
Node* getItem(int index)
{
if (index>=0)
{
if (index==0)
{
return list.head;
}
else
{
Node* node = list.head;
while (index-->0)node = node->next;
return node;
}
}
}
//输出链表
void ToString()
{
Node* _node = list.head;
if (_node!=NULL)
{
printf("%2d",_node->data);
while (_node->next!=NULL)
{
_node = _node->next;
printf("%2d ",_node->data);
}
}
}
int main(void)
{
Node node0 ={0,NULL};
Insert(&node0);
Node node1 = {1,NULL};
Insert(&node1);
Node node2 = {2,NULL};
Insert(&node2);
Node node3 = {3,NULL};
Insert(&node3);
ToString();
int _itenIndex = 2;
Node* _item = getItem(_itenIndex);
printf("\nlist[%d]=%d\n",_itenIndex,_item->data);
return 0;
}
beango
2009-6-10
*/
#include <stdio.h>
typedef struct _Node
{
int data;
struct _Node* next;
}Node;
typedef struct _List
{
Node* head;
}List;
List list;
//增加节点到链表的最未端
void Insert(Node* node)
{
Node* _head = list.head;
if (_head==NULL)
{list.head = node;node->next = NULL;}
else
{
Node* _node = _head;
while (_node->next!=NULL)
_node = _node->next;
_node->next = node;
node->next = NULL;
}
}
//获取索引处的元素
Node* getItem(int index)
{
if (index>=0)
{
if (index==0)
{
return list.head;
}
else
{
Node* node = list.head;
while (index-->0)node = node->next;
return node;
}
}
}
//输出链表
void ToString()
{
Node* _node = list.head;
if (_node!=NULL)
{
printf("%2d",_node->data);
while (_node->next!=NULL)
{
_node = _node->next;
printf("%2d ",_node->data);
}
}
}
int main(void)
{
Node node0 ={0,NULL};
Insert(&node0);
Node node1 = {1,NULL};
Insert(&node1);
Node node2 = {2,NULL};
Insert(&node2);
Node node3 = {3,NULL};
Insert(&node3);
ToString();
int _itenIndex = 2;
Node* _item = getItem(_itenIndex);
printf("\nlist[%d]=%d\n",_itenIndex,_item->data);
return 0;
}