剑指offer链表的基本操作之创建插入删除
Posted parzulpan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指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;
}
以上是关于剑指offer链表的基本操作之创建插入删除的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode刷题笔记之链表篇剑指 Offer 18. 删除链表的节点