首页 > 其他 > 详细

动态链表及其基本功能的实现

时间:2020-03-13 02:04:31      阅读:98      评论:0      收藏:0      [点我收藏+]
/*
动态创建一个链表:动态内存申请+模块化设计
1、创建链表
headNode指针 
2、创建结点
3、插入节点
4、删除节点
5、打印遍历链表(测试) 
*/ 
#include <stdio.h>
#include <stdlib.h> 
struct Node{
    int data;           //数据域 
    struct Node* next;  //指针域 
}N;
struct Node* creatList(){
    struct Node* headNode = (struct Node*)malloc(sizeof(struct Node));
    //headNode变成了结构体变量
    
    headNode->next = NULL;
    return headNode;//返回头节点地址 
    
}//创造链表 
struct Node* createNode(int data){

    struct Node* Node = (struct Node*)malloc(sizeof(struct Node));
    Node->data=data;
    Node->next=NULL;
    return Node;//返回结点地址 
} //创造节点 
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){
    struct Node* NewNode = createNode(data);
    NewNode->data = data;
    NewNode->next = headNode->next;
    headNode->next = NewNode;
} //头插法
void deleteNodeByAppoint(struct Node* headNode,int data){
    struct Node* posNode = headNode->next;
    struct Node* posNodeFront = headNode;
    if(posNode == NULL) printf("表空,任务失败");
    else{
        while(posNode->data != data){
          posNodeFront = posNode;
          posNode = posNode->next;
          if(posNode == NULL){
          printf("表尽,任务失败");
          return;    
    }//if
        }//while
        posNodeFront->next=posNode->next;
        free(posNode);
    } 
} //删除指定结点 
int main(){
    struct Node* list=creatList();
    insertNodeByHead(list,1);
    insertNodeByHead(list,2);
    insertNodeByHead(list,3);
    printList(list);
    deleteNodeByAppoint(list,2);
    printList(list);
    system("pause"); 
    return 0;
}

 

动态链表及其基本功能的实现

原文:https://www.cnblogs.com/OKDA/p/12483740.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!