C语言实现链表

在此记录一下自己在学习链表过程中总结的一些链表的构建方法

最常见的

#include<stdio.h>
#include<stdlib.h>//不要忘记,malloc要使用
//创立节点
typedef struct ListNode {
	int data;
	struct ListNode* Next;
}ListNode;

//记录整体链表信息的结构体,在后续操作的时候可以直接修改相对应的元素
typedef struct List {
	ListNode* head;
	ListNode* tail;   //可用于记录前驱节点
}List;



//单向链表的创立
//最常规的方法(应用于顺序输入)
int main()
{
	List *list;
	list = (List*)malloc(sizeof(list));
	list->head = NULL;
	list->tail = NULL;
	ListNode *current;
	int value = 0;
	do{
		current = (ListNode*)malloc(sizeof(ListNode));
		scanf_s("%d",&value);
		if (value) //若value不符合条件的时候会跳出,再进入while判断则结束循环
		{
			current->data = value;
			current->Next = NULL;
			//在链表中对头节点的操作一定要注意
			if (list->head==NULL)
			{
				list->head = current;
		     }
			if(list->tail)
			{
				list->tail->Next = current;
			}
			//用tail 记录当下节点,很快current就要被更新啦
			list->tail = current;
		}
	} while (value);
		return 0;
}
头插法
#include <stdio.h>
#include <stdlib.h>

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

struct ListNode *createlist();

int main()
{
    struct ListNode *p, *head = NULL;

    head = createlist();
    for ( p = head; p != NULL; p = p->next )
        printf("%d ", p->data);
    printf("\n");

    return 0;
}

/* 你的代码将被嵌在这里 */
struct ListNode *createlist(){
     int number;	
	struct ListNode *tail=NULL,*current=NULL,*head=NULL;
	do{
		scanf("%d",&number);
		if(number!=-1){
		current=NULL;
		current=(struct ListNode*)malloc(sizeof(struct ListNode));
		current->data=number;
		current->next=tail;
		tail=current;
		}
		
    }while(number!=-1);
	head=current;
    return head;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值