程序的本质是数据结构+算法
不同的数据结构对应不同的算法
创建单向链表
Node * createList()
{
Node * head = (Node *)malloc(sizeof(Node));
head->next = NULL;
return head;
}
删除链表的某个元素
void deleteList(Node * head, Node *pfind)//前驱
{
if (NULL == pfind->next) // 如果当前 pfind后面没元素了,不能使用赋值的形式进行操作
{
while (head->next != pfind)
{
head = head->next;
}
head->next = pfind->next;
free(pfind);
}
else
{
pfind->data = pfind->next->data; // 使用赋值的形式进行操作
Node * t = pfind->next;
pfind->next = pfind->next->next;
free(t);
}
}
使用场景:
Node *pfind = searchList(head, 6);
if (pfind != NULL) {
printf("find in the list\n");
deleteList(head, pfind);
}
删除链表
void destoryList(Node * head)
{
Node * t;
while (head)
{
t = head->next;
free(head);
head = t;
}
}
对链表元素排序
void popSortList(Node * head)//冒泡排序
{
Node * p, *q, *pre;
int len = lenList(head);
for (int i = 0; i < len - 1; i++)
{
pre = head;
p = head->next;
q = p->next;
for (int j = 0; j < len - 1 - i; j++)
{
if (p->data > q->data)
{
pre->next = q;
p->next = q->next;
q->next = p;
pre = pre->next;
q = p->next;
continue;
}
pre = pre->next;
p = p->next;
q = q->next;
}
}
}
链表逆转
遍历链表中所有结点,依次将各结点从链表中抽出,插到头结点和第一个数据结点之间
void reverseList(Node * head)
{
Node * cur = head->next;
head->next = NULL; // 切断链表,分裂为头和没有头的链表
Node *t;
while(cur)
{
t = cur;
cur = cur->next;
t->next = head->next; // 让当前元素有指向
head->next = t; // 让头结点指向当前元素
}
}