zoukankan      html  css  js  c++  java
  • 【剑指Offer】链表的基本操作之创建、插入、删除

    // C++
    
    #include<iostream>
    using namespace std;
    
    //链表的定义
    struct ListNode
    {
        int val;
        ListNode* next;
        ListNode(int n) :val(n), next(nullptr) {}
    };
    
    //链表的打印
    void printList(ListNode* head)
    {
        ListNode* pT = head;
        while (pT != nullptr)
        {
            cout << pT->val << " ";
            pT = pT->next;
        }
    }
    
    //链表的创建(头插法),注意打印时候倒着打印
    ListNode* createListA(ListNode* head, int* arr, int len)
    {
        ListNode* pB = head;
        for (int i = 0; i < len; ++i)
        {
            ListNode* pA = new ListNode(0);    //注意:
            pA->val = arr[i];
            pA->next = pB->next;
            pB->next = pA;
        }
        head = head->next;    //不要初始的头结点,否则会打印出0
        return head;
    }
    
    //链表的创建(尾插法)
    ListNode* createListB(ListNode* head, int* arr, int len)
    {
        ListNode* pB = head;
        for (int i = 0; i < len; ++i)
        {
            ListNode* pA = new ListNode(0);    //注意:
            pA->val = arr[i];
            pB->next = pA;
            pB = pA;
        }
        head = head->next;    //不要初始的头结点,否则会打印出0
        pB->next = nullptr;    //注意尾插法最后需要置空
        return head;
    }
    
    //链表节点的插入
    void insertVarofList(ListNode* head, int pos, int val)
    {
        int cnt = 0;
        ListNode* temp = new ListNode(val);
        while (head != nullptr)
        {
            head = head->next;
            ++cnt;
            if (cnt == pos)
            {
                temp->next = head->next;    //注意:顺序不能改变
                head->next = temp;
                break;
            }
        }
    }
    
    //链表节点的删除
    void deleteValofList(ListNode* head, int pos)
    {
        int cnt = 0;
        ListNode* temp = new ListNode(0);
        while (head != nullptr)
        {
            head = head->next;
            ++cnt;
            if (cnt == pos)
            {
                temp= head->next;    //令temp指向被删除节点
                head->next = temp->next;
                delete temp;
                break;
            }
        }
    }
    
    int main()
    {
        int arr[] = { 10,15,96,18,2,22,6,2 };
        ListNode* head = new ListNode(0);
        ListNode* L = createListB(head, arr, 8);
        printList(L);
        cout << endl;
    
        insertVarofList(L, 3, 100);
        printList(L);
        cout << endl;
    
        deleteValofList(L, 3);
        printList(L);
        cout << endl;
    
        return 0;
    }
    
  • 相关阅读:
    Flexbox布局(转)
    css兼容性
    本地存储 localStorage/sessionStorage/cookie
    正则去掉字符串空格
    ajax请求成功或失败的参数
    怎样实现页面跳转和刷新
    new Date()时间对象
    列车时刻表查询 jqm/ajax/xml
    jquery mobile 学习总结
    响应式学习总结
  • 原文地址:https://www.cnblogs.com/parzulpan/p/13394537.html
Copyright © 2011-2022 走看看