• C++——数据结构之链表


    直接上例子

    int main()
    {
        int a1[]={3,4,2};
        int a2[]={4,6,5};
    
        Listnode *head=NULL,*temp;
        head=(Listnode*)malloc(sizeof(Listnode));//头节点
        head->next=NULL;
        /*1.new node in head->next,head on the botom 
        for (int i=0;i<3;i++)
        {
            temp=(Listnode*)malloc(sizeof(Listnode));
            temp->val=a1[i];
    
            temp->next=head->next;//先把上一次插入的链表打断,接入新插入节点的后面
            head->next=temp;//然后把链条接入头节点的下面。于是:每一个新节点都插入到头节点之后,于是倒序了
    }*/ 

    /*2. */

    Listnode *r;
    r
    =head; //地址
    for (int i=0;i<3;i++)
    {
      temp
    =(Listnode*)malloc(sizeof(Listnode));
      temp
    ->val=a1[i];
      r
    ->next=temp; //每一个新节点都插入到了原来链条的最后,并且链条向后走了一步
      r
    =temp; //更新最后一个节点
    }
    r
    ->next=NULL; //把最后节点指向NULL

    temp
    =head->next;//将链表移到首结点开始打印
    while (temp)
    {
      cout
    <<"->"<<temp->val<<endl;
      temp
    =temp->next;
    }
    return 0;
    }

    1.通过数组建链表

    int nums2[] = {1,3,5};
    ////////////////////1.
    ListNode* head2=new ListNode(nums2[0]);
    r=head2;
    for(int i=1;i<sizeof(nums2)/sizeof(int);i++)
    {
        r->next=new ListNode(nums2[i]);
        r=r->next;
    }
    /////////////2.
    ListNode* createList(int a[], int n)
    {
        ListNode *head=NULL, *p=NULL;
        for(int i=0; i<n; i++){
            if (head == NULL){
                head = p = new ListNode(a[i]);
            }else{
                p->next = new ListNode(a[i]);
                p = p->next;
            }
        }
        return head;
    }
    ListNode* p1 = createList(nums2, sizeof(nums2)/sizeof(int));

    2.链表反转

    ListNode* reverse(ListNode* first,ListNode* last)
        {
            ListNode* prev=NULL;
            if(!first || !last) return prev;
    
            ListNode* tmp=NULL;
            while(first && first!=last){
                tmp=first->next;
                first->next=prev;
                prev=first;
                first=tmp;
            }
            last->next=prev;
            return last;
        }
  • 相关阅读:
    June 1. 2018 Week 22nd Friday
    【Android开发】【布局】几个常用布局构成的简单demo
    【Android开发】【布局】各种TabLayout样式
    【Android开发】【数据库】Realm For Android
    【Android开发】jarsigner重新打包apk
    【Android开发】Coding + git命令行基本使用
    【MarkDown】使用
    【Android Studio】Gradle统一管理版本号引用配置
    【Android开发】EasyPermissions 请求权限
    【Android开发】Android6.0请求权限方式
  • 原文地址:https://www.cnblogs.com/yrm1160029237/p/11055505.html
Copyright © 2020-2023  润新知