##从尾到头输出单链表
void ReversePrint(SListNode *phead) //phead为链表头指针
{
SListNode *head = phead;
SListNode *tail = head;
if (phead == NULL) //链表为空
{
printf("the list was empty!");
return;
}
if (head->next == NULL) //链表内仅有一个节点
{
printf("%d->NULL", head->data);
}
else//链表内至少2节点
{
ReversePrint(head->next);
printf("%d->", head->data);
}
}
##删除一个无头单链表的非尾节点
//删除一个无头单链表的非尾节点
void DelListNode(SListNode **pos) //pos是指向链表头指针的二级指针
{
assert(pos);
SListNode *next = (*pos)->next;
(*pos)->data = next->data;
(*pos)->next = next->next;
free(next);
}
##在无头单链表的一个节点前插入一个节点(不能遍历链表)
void PlistInsert(SListNode **pos, DataType x)
{
assert(pos);
if ((*pos)->next == NULL)
{
SListNode *newnode = BuySListNode((*pos)->data);
(*pos)->next = newnode;
(*pos)->data = x;
}
else
{
SListNode *next = (*pos)->next;
SListNode *newnode = BuySListNode((*pos)->data);
newnode->next = next;
(*pos)->next = newnode;
(*pos)->data = x;
}
}
##单链表实现约瑟夫环(JosephCircle)
void Joseph(SListNode **fflag,int x) //链表已构成环
{
SListNode *flag = (*fflag);
SListNode *next = (*fflag);
if (flag->next ==flag) //链表内部只有一个节点
{
printf("%d", flag->data);
return;
}
while (flag->next != flag) //链表内至少2个节点
{
SListNode *del =NULL;
int num = x;
for (int i = 1;i < x-1;i++)
{
flag = flag->next;
}
del = flag->next;
next = flag->next->next;
printf("%d ", del->data);
flag->next = next;
free(del);
flag = next;
}
printf("%d", flag->data);
}
##逆置/反转单链表
SListNode *reverse_list(SListNode **pphead)
{
assert(pphead);
if ((*pphead)->next == NULL) //链表只有一个节点
{
return *pphead;
}
//链表至少有2个节点
SListNode *p1 = *pphead;
SListNode *p2 = (*pphead)->next;
SListNode *p3 = (*pphead)->next->next;
while (p3)
{
p2->next = p1;
p1 = p2;
p2 = p3;
p3 = p3->next;
}
p2->next = p1;
(*pphead)->next = NULL;
return p2;
}