在此记录一下自己在学习链表过程中总结的一些链表的构建方法
最常见的
#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;
}