单链表与循环链表创建

发布时间:2024年01月13日

链表

struct List
{
	int data;
	struct List* next;
}

创建链表

单链表
实现
struct List* listCreate()
{
	int data;
    struct List* head = NULL;
    struct List* pre = NULL;
    struct List* current = NULL;
    
    while(scanf("%d",&data) && data != -1)
    {
        current = (struct List*)malloc(sizeof(struct List));
        if(head == NULL)
            head = current;
        else
            pre->next = current;
        current->next = NULL;
        current->data = data;
        pre = current;
    }
    return head;
}
错例
struct List* listCreate()
{
	int data;;
	struct List* current = NULL;
	struct List* head = current;
	while (scanf("%d", &data) && data != -1)
	{
		current = (struct List*)malloc(sizeof(struct List));
		if (head == NULL)
			head = current;
		current->data = data;
		current = current->next;
	}
	return head;
}

在使用malloc函数开辟的空间中,不要进行指针的移动,因为一旦移动之后可能出现申请的空间和释放空间大小的不匹配

循环链表

单独创建
struct List* circle_listCreate()
{
	int data;
    struct List* head = NULL;
    struct List* pre = NULL;
    struct List* current = NULL;
    
    while(scanf("%d",&data) && data != -1)
    {
        current = (struct List*)malloc(sizeof(struct List));
        if(head == NULL)
            head = current;
        else
            pre->next = current;
        current->next = head;
        current->data = data;
        pre = current;
    }
    return head;
}

删除节点

实现方式一:

struct list* listDelete(struct list* L,int data)
{
    struct list* pre = L;
    struct list* head = L;
    struct list* kill;
    
    while(head != NULL && head->data == m)
    {
        kill = head;
        head = head->next;
        free(kill);
    }
    if(head == NULL)
        return head;
    
    pre = head;
    kill = head->next;
    while(kill!=NULL)
    {
        if(kill->data == m)
        {
            pre->next = kill->next;
            free(kill);
            kill = pre->next;
        }
        else
        {
            pre = kill;
            kill = kill->next;
        }
    }
    return head;
}

实现方式二:

struct list* listDelete(struct list** L,int data)
{
    struct list* head = (*L), * pre = (*L);
    struct list* newL = *L;
    struct list* kill = NULL;
    while (*L !- NULL)
    {
        if((*L)->data == data)
        {
            if((*L) == newL)
                newL ==newL->next;
            else
                pre->next = (*L)->next;
            kill = (*L);
            (*L) = (*L)->next;
            free(kill);
        }
        else
        {
            pre = (*L);
            (*L) = (*L)->next;
        }
    }
    *L = newL;
    return head;
}
文章来源:https://blog.csdn.net/Star__01/article/details/135563273
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。