单链表的基本操作-单链表的创建、插入、删除结点等

序言

本文主要包括:

(1)单链表的创建

(2)创建结点

(3)打印结点

(4)链表的插入【头插法】

(5)链表的删除【指定位置删除】

适合新手初步认识学习单链表的基本操作

一、代码:

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
//结构体----结点由数据域+指针域构成 
struct Node {
    int data;//数据域 
    struct Node* next;//指针域 
};
//创建链表(表头)
struct Node* createList(){
    struct Node* headNode=(struct Node*)malloc(sizeof(struct Node));
    //headNode 成为了结构体变量
    //变量使用前必须初始化 
    //headNode->data=1;//一般不初始化数据 
    headNode->next=NULL;
    return headNode;      
}
//创建结点
struct Node* createNode(int data){
    struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
    //初始化新结点 
    newNode->data=data;
    newNode->next=NULL;
    return newNode;
 } 
 //打印结点(遍历结点) 
 void printList(struct Node* headNode  ) {
     struct Node* pMove=headNode->next;//打印指针指向头结点下一个结点 
     while(pMove) {
         printf("%d\t",pMove->data);
         pMove=pMove->next;    
     }        
     printf("\n");
 }

//链表的插入:插入结点---插入那个链表、插入结点的数据是多少 
  void insertNodeByHead(struct Node* headNode,int data){
  //1、创建一个插入结点
  struct Node* insertNode=createNode(data); //调用createNode方法创建一个新的结点 
    insertNode->next=headNode->next;
    headNode->next=insertNode;
} 
//链表的删除:指定的位置删除 ---删除那个链表、删除的数据是多少 
void deleteNodeByAppoin(struct Node* headNode,int posData) {
    struct Node* posNode=headNode->next;
    struct Node* posNodeFront=headNode;
    if(posNode==NULL)
        printf("链表为空!"); 
    else{
        while(posNode->data!=posData){
            posNodeFront=posNode;
            posNode=posNodeFront->next;
            if(posNode==NULL){
                printf("无法找到指定位置");
                return;
            }            
        }
        posNodeFront->next=posNode->next;
        free(posNode);
    }    
} 
int main() {
    struct Node* list=createList();//创建一个名为list的链表 
    printf("插入前链表中的数据:\n"); 
    printList(list);
    printf("插入后链表中的数据:\n"); 
    insertNodeByHead(list,3);//向链表list插入数据---3 
    insertNodeByHead(list,2);//向链表list插入数据---2 
    insertNodeByHead(list,1);//向链表list插入数据---1 
    printList(list);         //打印链表 list 
    printf("删除后链表中的数据:\n"); 
    deleteNodeByAppoin(list,2);//删除链表中数据为2的 
    printList(list);
    system("pause");
    return 0; 
}

 

 

二、运行结果:

posted @ 2019-12-17 16:18  陈晓晨不吃香菜  阅读(3069)  评论(0编辑  收藏  举报