码迷,mamicode.com
首页 > 其他好文 > 详细

【剑指offer】链表的基本操作之创建、插入、删除

时间:2020-07-29 09:59:12      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:iostream   var   turn   顺序   off   str   头结点   bre   不能   

// 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;
}

【剑指offer】链表的基本操作之创建、插入、删除

标签:iostream   var   turn   顺序   off   str   头结点   bre   不能   

原文地址:https://www.cnblogs.com/parzulpan/p/13394537.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!