zoukankan      html  css  js  c++  java
  • 带头结点的单链表

    代码:

    /*
     *带头节点的单链表
     */
    #include<iostream>
    #include<stdlib.h>
    using namespace std;
    
    typedef struct ListNode
    {
        int data;
        struct ListNode* next;
    } Node,*PNode;
    
    //新建结点,num表示结点个数
    PNode NewNode(int num)
    {
       //新建头结点
        PNode head=(PNode)malloc(sizeof(Node));
        if(head==NULL)
        {
            cout<<"头节点内存分配失败!";
            exit(0);
        }
    
        PNode temp=head;
        temp->next=NULL;
    
        for(int i=0; i<num; i++)
        {
            //当前结点的数据
            int num;
            cin>>num;
            //新节点
            PNode node=(PNode)malloc(sizeof(Node));
            if(node==NULL)
            {
                cout<<"节点内存分配失败!";
                exit(0);
            }
            node->data=num;
    
            temp->next=node;
            temp=node;//使temp指向新建结点
        }
        return head;//返回头结点
    }
    //删除结点,temp表示删除链表的第几个结点
    void Free(PNode node,int temp)
    {
        int num=1;
        while(temp!=num)
        {
            node=node->next;
            num++;
        }
        node->next=node->next->next;
    }
    //在尾部插入结点,temp表示插入的数据
    void Insertoftail(PNode node,int temp)
    {
        while(node->next!=NULL)//注意判断条件是node->next!=NULL;指向最后一个结点就停止
        {
            node=node->next;
        }
        PNode New=(PNode)malloc(sizeof(Node));
        if(New==NULL)
        {
            cout<<"节点内存分配失败!";
            exit(0);
        }
        New->data=temp;
        node->next=New;
    }
    //根据链表及数据,查找所在位置,只能查找第一个找到的
    void Search(PNode node,int temp)
    {
        node=node->next;
        int num=0;
        while(node!=NULL)
        {
            num++;
            if(node->data==temp)
            {
                cout<<"您查找的数字"<<temp<<""<<num<<""<<endl;
                return;
            }
            node=node->next;
        }
        cout<<"未找到!"<<endl;
    }
    //输出链表数据
    void Printf(PNode node)
    {
        node=node->next;//头节点需要跳过
        while(node!=NULL)
        {
            cout<<node->data<<" ";
            node=node->next;
        }
        cout<<endl;
    }
    int main()
    {
        ListNode* head=NewNode(7);//新建长度为7的链表,逐个输入数据
        Printf(head);//输出当前链表数据
        Search(head,8);//查找数据为8的结点
        Insertoftail(head,99);//在尾部插入数据为99的结点
        Printf(head);//输出当前链表数据
        Free(head,1);//删除第一个结点
        Printf(head);//输出当前链表数据
        return 0;
    }

     实验截图:

  • 相关阅读:
    Java中四种引用类型
    使用VisualVM查看Java Heap Dump
    Java程序性能分析工具Java VisualVM(Visual GC)—程序员必备利器
    JVM性能调优监控工具jps、jstack、jmap、jhat、jstat、hprof使用详解
    设计模式2---建造者模式(Builder pattern)
    设计模式1---单例模式(Singleton pattern)
    移动端网络优化
    Http请求的 HttpURLConnection 和 HttpClient
    第四章 Activity和Activity调用栈分析 系统信息与安全机制 性能优化
    Android模块化编程之引用本地的aar
  • 原文地址:https://www.cnblogs.com/handsometaoa/p/12067042.html
Copyright © 2011-2022 走看看