707. 设计链表

struct node
{
	int val;
	struct node* next;
};

typedef struct {
	struct node* first;
} MyLinkedList;

MyLinkedList* myLinkedListCreate()
{
	MyLinkedList* obj = malloc(sizeof(MyLinkedList));
	obj->first = NULL;
	return obj;
}

int myLinkedListGet(MyLinkedList* obj, int index)
{
	struct node* p;

	if (index < 0)
	{
		return -1;
	}

	for (p = obj->first; p != NULL; p = p->next)
	{
		if (index == 0)
		{
			return p->val;
		}
		index--;
	}

	return -1;
}

void myLinkedListAddAtHead(MyLinkedList* obj, int val)
{
	struct  node* new_node = malloc(sizeof(struct node));
	new_node->val = val;
	new_node->next = obj->first;
	obj->first = new_node;
}

void myLinkedListAddAtTail(MyLinkedList* obj, int val)
{
	struct node* p;
	struct  node* new_node = malloc(sizeof(struct node));

	if (obj->first == NULL)
	{
		myLinkedListAddAtHead(obj, val);
		return;
	}

	for (p = obj->first; p != NULL && p->next != NULL; p = p->next)
		;
	new_node->val = val;
	new_node->next = NULL;
	p->next = new_node;
}

void myLinkedListAddAtIndex(MyLinkedList* obj, int index, int val)
{
	struct node* prev, * cur;
	struct  node* new_node = malloc(sizeof(struct node));

	if (index < 0)
	{
		myLinkedListAddAtHead(obj, val);
		return;
	}

	for (prev = NULL, cur = obj->first;
		cur != NULL && index != 0;
		prev = cur, cur = cur->next, index--
		)
		;
	if (index != 0)
	{
		return;
	}
	else if (cur == NULL)
	{
		myLinkedListAddAtTail(obj, val);
	}
	else if (prev == NULL)
	{
		myLinkedListAddAtHead(obj, val);
	}
	else
	{
		new_node->val = val;
		prev->next = new_node;
		new_node->next = cur;
	}
}

void myLinkedListDeleteAtIndex(MyLinkedList* obj, int index) 
{
	struct node* prev, * cur;

	if (index < 0)
	{
		return;
	}

	for (prev = NULL, cur = obj->first;
		cur != NULL && index != 0;
		prev = cur, cur = cur->next, index--
		)
		;
	if (cur == NULL)
	{
		return;
	}
	else if (prev == NULL)
	{
		obj->first = cur->next;
		free(cur);
	}
	else if (index != 0)
	{
		return;
	}
	else
	{
		prev->next = cur->next;
		free(cur);
	}
}

void myLinkedListFree(MyLinkedList* obj) 
{
	if (obj->first!=NULL)
	{
		myLinkedListDeleteAtIndex(obj, 0);
	}
	free(obj);
}

上一篇:Linux查看物理CPU个数、核数、逻辑CPU个数


下一篇:faiss-2: 快速入门