【剑指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;
}
上一篇:单链表实现一元多项式加法与乘法


下一篇:PAT A1009 Product of Polynomials (25分)