-
链表的结构
typedef struct Node
{
DataType data;
struct Node* next;
}Node, *pNode;
-
链表的基本函数
//初始化
void InitLinList(pNode* pn)
{
assert(pn);
*pn = NULL;
}
//创建新的节点
Node* CreatNewNode(DataType d)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = d;
node->next = NULL;
return node;
}
//打印
void PrintLinList(pNode first)
{
Node* cur = first;
printf("first-->");
while (cur != NULL)
{
printf("%d-->", cur->data);
cur = cur->next;
}
printf("NULL\n");
}
//尾插
void PushBack(pNode* pn, DataType d)
{
assert(pn);
Node* cur = *pn;
Node* newnode = CreatNewNode(d);
//链表为空
if (*pn == NULL)
{
*pn = newnode;
return;
}
//至少有一个数据
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = newnode;
}
// 查找(顺序查找) 找到了,返回所在结点地址,没有找到返回 NULL
Node* FindLinList(pNode* pn, DataType d)
{
assert(pn);
Node* cur;
for (cur = *pn; cur != NULL; cur = cur->next)
{
if (cur->data == d)
{
return cur;
}
}
return NULL;
}
一、从尾到头打印单链表
-
递归
void TailPrintR(Node* pfirst)
{
if (pfirst == NULL)
{
return;
}
TailPrintR(pfirst->next);
printf("%d ", pfirst->data);
}
- 非递归
void TailPrint(Node* pfirst)
{
Node* cur = pfirst;
Node* last = NULL;
while (last != pfirst)
{
cur = pfirst;
while (cur->next != last)
{
cur = cur->next;
}
printf("%d ", cur->data);
last = cur;
}
}
二、删除一个无头单链表的非尾节点(不能遍历链表)
void RemoveNoHeadNotTail(Node* Del)
{
assert(Del->next != NULL);
Node* next = Del->next;
Del->data = next->data;
Del->next = next->next;
free(next);
}