标签:
1.单链表
单链表的结点类型node定义:
typedef struct linknode
{
int data;
struct linknode *node;
};
<1>.建立单链表
void CreateSingleLink()
{
node *head, *p, *s;
int tempValue;
bool bCycle = true; //bCycle循环控制变量
head = (node *)malloc(sizeof(node)); //建立头结点
p = head;
while (bCycle)
{
scanf("%d", &tempValue);
if (0 != tempValue) //以0标志结束
{
s = (node *)malloc(sizeof(node)); //建立下一个结点
s->data = tempValue;
p->next = s; //把新结点连接到前面建立的链表中
p = s;
}
else
{
bCycle = false;
}
}
p->next = NULL; //如果是循环链表,则改为p->next = head;
p = head;
head = head->next;
free(p); //删除头结点
}
<2>.单链表查找结点
bool FindNode(node *head, int iValue)
{
bool bFind = false;
node *p;
//if 普通链表
p = head;
//else 循环列表
//if (head->data == iValue)
//{
// bFind = true;
// return bFind;
//}
//p = head->next;
while (p!=NULL && p->data!=iValue)
{
p = p->next;
}
if (p != NULL)
{
bFind = true;
}
return bFind;
}
<3>.单链表长度
//普通链表
int LengthLink(node *head)
{
int iLength = 0;
node *p;
p = head;
while (p != NULL)
{
p = p->next;
iLength++;
}
return iLength;
}
//循环链接
int LengthLink(node *head)
{
int iLength = 0;
node *p;
if (head == NULL) //空链表
{
return iLength;
}
p = head->next;
iLength = 1;
while (p != NULL)
{
p = p->next;
iLength++;
}
return iLength;
}
<4>.单链表插入结点
bool InsertNode(node *head, int i, int iValue)
{
node *s, *p;
int j;
bool bInsert = false;
s = (node *)malloc(sizeof(node)); //建立待插入结点
s->data = iValue;
if (i == 0)
{
//表头插入结点
s->next = head;
head = s;
bInsert = true;
return bInsert;
}
p = head;
j = 1;
while (p!=NULL && j<i)
{
j++;
p = p->next;
}
if (p != NULL)
{
//查找成功,将s插入到其后
s->next = p->next;
p->next = s;
bInsert = true;
}
return bInsert;
}
<5>.单列表删除结点
bool DeleteNode(node *head, int iValue)
{
node *p, *q;
bool bDelete = false;
if (head == NULL)
{
//链表为空,下溢处理
return bDelete;
}
if (head->data == iValue)
{
//表头为删除结点
p =head;
head = head->next;
free(p);
bDelete = true;
return bDelete;
}
q = head;
p = head->next; //从第二个结点开始查找值为iValue的结点
while (p!=NULL && p->data!=iValue)
{
if (p->data != iValue)
{
q = p;
p = p->next;
}
}
if (p != NULL)
{
//找到结点,作删除处理
q->next = p->next;
free(p);
bDelete = true;
}
return bDelete;
}
标签:
原文地址:http://www.cnblogs.com/sz-leez/p/4607721.html