初始化链表的四种方法(有无头结点以及表头(尾)插入法)

首先定义初始条件

typedef struct Node{
    int val;
    struct Node *next;
}Node, *LinkedList;
LinkedList HasHeadNodeIntiListAtEnd();
LinkedList HasHeadNodeIntiListAtStart();
LinkedList NoHeadNodeIntiListAtStart();
LinkedList NoHeadNodeIntiListAtEnd();

①无头结点的表尾插入法

LinkedList NoHeadNodeIntiListAtEnd(){
    LinkedList prev, current, head;
    int firstNodeVal;

    //首先判断第一个值有没有输入,若没有则直接返回结点
    if(scanf("%d", &firstNodeVal) != EOF){
        prev = (LinkedList)malloc(sizeof(Node));
        head = prev;//保存第一个结点的位置
        prev->val = firstNodeVal;
    }
    else{
        return head;
    }

    //现在已经确保了第一个节点有输入,若第二个结点不输入则会跳过以下循环
    current = (LinkedList)malloc(sizeof(Node));
    while(scanf("%d", &current->val) != EOF){
        prev->next = current;
        prev = current;
        current = (LinkedList)malloc(sizeof(Node));
    }
    prev->next = NULL;//选用prev而不是current是为了避免没有输入第二个结点的情况
    return head;
}

②无头结点的倒序插入法(也就是将第一个结点放到链表的最后位置)

LinkedList NoHeadNodeIntiListAtStart(){
    LinkedList prev, current;
    int firstNodeVal;
    if(scanf("%d", &firstNodeVal) != EOF){
        current = (LinkedList)malloc(sizeof(Node));
        current->val = firstNodeVal;
        current ->next = NULL;//确保最后一个结点的next指针指向NULL
    }
    prev = (LinkedList)malloc(sizeof(Node));
    while(scanf("%d", &prev->val) != EOF){
        prev->next = current;
        current = prev;
        prev = (LinkedList)malloc(sizeof(Node));
    }
    return current;//不能返回prev因为最后prev是一个新分配的地址没有指向任何一个地方,同时也确保了没有输入第二个结点的情况
}

③有头节点的表尾插入法

//有头结点的时候第一个结点就不需要特殊对待
LinkedList HasHeadNodeIntiListAtEnd(){
   LinkedList prev, current, headNode;
   headNode = (LinkedList)malloc(sizeof(Node));
   prev = headNode;
   int value;
   while(scanf("%d", &value) != EOF){
       current = (LinkedList)malloc(sizeof(Node));
       current->val = value;
       prev->next = current;
       prev = current;
   }
   prev->next = NULL;
   return headNode;
}

④有头结点的表头插入法

LinkedList HasHeadNodeIntiListAtStart(){
    LinkedList next, headNode;
    headNode = (LinkedList)malloc(sizeof(Node));
    headNode->next = NULL;
    int value;
    while(scanf("%d", &value) != EOF){
        next = (LinkedList)malloc(sizeof(Node));
        next->val = value;
        next->next = headNode->next;
        headNode->next = next;
    }
    return headNode;
}

To be Continued

你可能感兴趣的:(链表)