数据结构——算法之(027)( 在O(1)时间内删除链表结点)

【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:Mr_chenping@163.com】

题目:在O(1)时间内删除链表结点。且不知道链表头

题目分析:

1、把要删除节点的下一个节点的数据复制到要删除的节点

2、把下一个节点删除

算法实现:

#include <stdio.h>
#include <stdlib.h>

typedef struct _list_node
{
	int        key;
	struct _list_node  *next;
}list_node;

void *list_insert(list_node *head, int key)
{
	list_node *p = head;
	while(p->next != NULL)
		p = p->next;
	list_node *node = calloc(1, sizeof(list_node));
	node->key = key;
	node->next = NULL;

	p->next = node;
}

void list_delete(list_node *del_node)
{
	list_node *p = del_node->next;
	del_node->key = p->key; /*copy data*/
	del_node->next = p->next;
	free(p);
}

void list_dispaly(list_node *head)
{
	list_node *p = head->next;
	printf("list:");
	while(p)
	{
		printf(" %d", p->key);
		p = p->next;
	}
	printf("
");
}

int main(int argc, char *argv[])
{
	list_node *head = calloc(1, sizeof(list_node));
	head->key = 0;
	head->next = NULL;

	list_insert(head, 1);	
	list_insert(head, 2);	
	list_insert(head, 3);	
	list_insert(head, 4);	
	list_insert(head, 5);

	list_dispaly(head);	
	list_delete(head->next->next);
	list_dispaly(head);	
	return 0;
}


原文地址:https://www.cnblogs.com/cxchanpin/p/6899852.html