test.rar 单链表常用操作
1、单链表的定义
2、单链表插入(头插入、尾插入、指定插入)
3、单链表删除(头删除、尾删除、指定删除)
4、单链表数据成员统计。
5、单链表查找。
6、销毁整个单链表。
1、单链表定义:
typedef struct _student
{
int id;
struct _student *next;
}student;
#define student_len sizeof(student)
student *student_head = NULL;
2、单链表插入
1)头插入
student *front = NULL ,*new = NULL;
while(data--->)
{
new = (student *)malloc(student_len);
if (NULL == new)
{
break;
}
memset(new, 0, outbound_task_s_t_len);
new->id = data->id;
new->next = front;
front = new;
}
2)尾插入
student *front = NULL ,*new = NULL ,*last = NULL;
while(data--->)
{
new = (student *)malloc(student_len);
if (NULL == new)
{
break;
}
memset(new, 0, student_len);
new->id = data->id;
if (NULL == last)
{
last = new;
front = new;
}
else
{
last->next = new;
last = new;
}
}
3)指定插入
student *a = NULL;
a = (student *)malloc(student_len);
if (NULL == a)
{
return 0;
}
memset(a, 0, student_len);
a->id = 6;
for (cur = student_head; NULL != cur; cur = cur->next)
{
if (a->id > cur->id) //插到数字的前面
{
if (NULL != prev)
{
prev->next = a;
a->next = cur;
}
else
{
a->next = cur;
student_head = a;
}
break;
}
prev = cur;
}
2、删除操作
1)删除一个指定的值
for (cur = student_head; NULL != cur; cur = cur->next)
{
if (cur->id == 6) //删除值为6的结点
{
if (NULL != prev)
{
prev->next = cur->next;
}
else
{
student_head = cur->next;
}
free(cur);
}
else
{
prev = cur;
}
}
2)删除一个指定的值
student *tmp = NULL;
cur = student_head;
while (cur)
{
tmp = cur;
if (cur->id == 6) //删除值为6的结点
{
if (NULL != prev)
{
prev->next = cur->next;
}
else
{
student_head = cur->next;
}
cur = cur->next;
free(tmp);
tmp = NULL;
}
else
{
prev = cur;
cur = cur->next;
}
}
3) 删除第一个结点:
//删除表中的第一个数据
cur = student_head;
student_head = cur->next;
free(cur);
4)删除表中的最后一个数据
cur = student_head;
while (cur)
{
tmp = cur;
if (cur->next == NULL) //最后一个结点
{
if (NULL != prev)
{
prev->next = cur->next;
}
else
{
student_head = cur->next;
}
cur = cur->next;
free(tmp);
tmp = NULL;
}
else
{
prev = cur;
cur = cur->next;
}
}
5)释放所有数据
cur = student_head;
while (cur)
{
tmp = cur;
cur = cur->next;
free(tmp);
tmp = NULL;
}
student_head = NULL;
阅读(245) | 评论(0) | 转发(0) |