星星博客 »  > 

2021-05-09

单链表

单链表的创建及打印

#include <stdio.h>
#include <stdlib.h>
struct Node{
    int data;
    struct Node *next;
};
struct Node *creatLink(){
    int data;
    struct Node *head = (struct Node *)malloc(sizeof (struct Node));
    head ->next = NULL;
    struct Node *tail = head;
    while(1){
        scanf("%d",&data);
        if(data == -1){
            break;
        }else{
            struct Node *temp = (struct Node *) malloc(sizeof (struct Node));
            temp->data = data;
            temp->next = NULL;
            tail->next = temp;
            tail = temp;
        }

    }
    return head->next;
}

void printLink(struct Node *head){
    while(head){
        printf("%d ",head->data);
        head = head->next;
    }
}



int main(){
    struct Node *head = creatLink();  
    printLink(head);
    return 0;
}

单链表插入节点

img

  • 将新结点的next指针指向插入位置后的结点;
  • 将插入位置前的结点的next指针指向插入结点;
//elem 要插入的节点; add 插入的位置 add不等于1,若插在头部,需单独处理
void insertNode(struct Node *head,int add,int elem){
    struct Node *temp = (struct Node*) malloc(sizeof (struct Node));
    temp ->data = elem;
    temp ->next = NULL;
    for(int  i=0; i<add-2 ; i++){
        head = head ->next;
    }
    temp ->next = head ->next;
    head ->next = temp;
}

单链表删除节点

当需要从链表中删除某个结点时,需要进行两步操作:

  • 将结点从链表中摘下来;
  • 手动释放掉结点,回收被结点占用的内存空间;
//del 要删除的节点位置 不能等于1,若删除头结点需单独处理
void deleteNode(struct Node *head, int del){
    for(int i=0; i<del-2; i++){
        head = head ->next;
    }
    struct Node *temp = head ->next;
    head->next = head->next->next;
    free(temp);
}

相关文章