已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
void insert_tail(link_node *phead, elem_type val) //创建循环链表
{
link_node *new_node = (link_node *)malloc(sizeof(link_node));
new_node->data = val;
link_node *temp = phead;
if (temp->next == NULL)
{
temp = new_node;
new_node->next = new_node;
}
else
{
temp = temp->next;
while (temp->next != phead->next)
{
temp = temp->next;
}
temp->next = new_node;
new_node->next = phead->next;
}
}
void link_process(link_node *phead, int k, int m) //从第k个结点开始计数,数到m的结点删除,下个结点继续循环
{
link_node *temp = phead->next, *p=phead;
while (temp->data != k)
temp = temp->next; //第k个
int i = 1;
while (temp->next != NULL)
{
while (i != m)
{
p = temp;
temp = temp->next;
i++;
}
printf("%d\n", temp->data);
p->next = temp->next;
free(temp); //删除
temp = p->next;
}
}
剑指offer中链表相关的题
从尾到头打印
(1)利用尾删法,在删除前打印尾结点
void print_list(listnode *phead)
{
listnode *temp = phead;
while (temp->next != NULL) //循环至尾结点
{
temp = temp->next;
while (temp->next == NULL)
{
printf("%d ", temp->data); //打印最后一个节点,并销毁
free(temp);
temp = phead;
}
}
}
(2)利用递归来实现,
void print_list(listnode *phead)
{
if (phead != NULL) //判断是否为空链表
{
if (phead->next != NULL) //判断是否为尾结点
{
print_list(phead->next);
}
printf("%d ", phead->data);
}
}
在O(1)时间删除结点
void delete_list(listnode *phead, listnode *deleted)
{
if (phead == 0 || deleted == 0)
return;
if (deleted->next != NULL) //要删除的结点不是尾结点
{
listnode *temp = deleted->next; //定义个指针,指向删除结点的下一结点
deleted->data = temp->data; //覆盖数据域
deleted->next = temp->next; //覆盖地址域
temp->next = NULL;
free(temp); //释放
}
}
这种个方法就不用循环查找要删除的节点,定义个指针保存该节点下一个节点的数据域和地址域,再用这个指针将要删除的节点覆盖。
输出倒数第k个结点
bool FindK_list(listnode *phead, unsigned int k)
{
listnode *temp = phead,*p;
if (phead->next == NULL || k == 0) //判断链表是否为空,k值是否为0
return NULL;
for (int i = 0; i < k - 1; i++) //temp先向后移动至k-1处
temp = temp->next;
p = phead;
while (temp->next != NULL) //temp移向尾节点,p移至k处
{
temp = temp->next;
p = p->next;
}
return p;
}
因为是单链表,无法回溯到倒数第k个节点,所以用两个指针,第一个指针走到k-1处,第二个指针再从头跟着一起移动。当地一个指针走到尾结点时,第二个指针刚好走到倒数第k个节点。
合并链表
listnode *Merger_list(listnode *phead1, listnode *phead2)
{
listnode *p;
if (phead1 == NULL) //phead1为空时返回表2
return phead2;
else if (phead2 == NULL) //phead2为空时返回表1
return phead1;
if (phead1->data > phead2->data)
{
p = phead2;
p->next = Merger_list(phead1, phead2->next);
}
else if (phead1->data = phead2->data)
{
p = phead2;
p->next = Merger_list(phead1->next, phead2->next);
}
else
{
p = phead1;
p->next = Merger_list(phead1, phead2->next);
}
}