C++如何构造出链表(以构造一个0~5的链表为例)
- 建立结点
class ListNode
{
int value;
ListNode* next;
};
- 结点建立连接
- 建立头指针,头结点。头指针指向头结点
ListNode* p = nullptr; ListNode* temp = new ListNode; p = temp;
- 循环新建结点,指针建立连接
for (int i = 1;i <= 5;i++) { ListNode* node = new ListNode; node->value = i; temp->next = node; temp = node; }
- 建立头指针,头结点。头指针指向头结点
C++中链表的特点
- 分散存储,充分利用存储空间。
- 单链表特点(后驱节点只有一或零个)
链表中元素的增加(位置从1开始)
- 首部
if (position == 1 || head == NULL)
{
new_node->next = head;
head = new_node;
}
ps:当原链表中头结点为NULL时,默认把新节点作为头结点。
- 中间或尾部
linknode* temp = head;//注意对头指针的保存
for (int i = 1;i < position - 1;temp = temp->next, i++);
new_node->next = temp->next;
temp->next = new_node;
- 注意对位置合法性的检查
if(position<1 || position > length +1 ) { cout << "位置参数错误" << endl; } int linknode::get_size(linknode* head) { int length = 0; linknode* temp = head; while (temp) { length++; temp = temp->next; } return length; }
链表中元素的删除
- 删除头结点
if (position == 1)
{
linknode* temp = head;
head = head->next;
delete temp;
}
- 删除中间或末尾的结点
linknode* p = head;
for (int i = 1;i < position - 1;p = p->next, i++);
linknode* temp = p->next;
p->next = p->next->next;
delete temp;
- 注意对特殊情况的判断
if (head == NULL) return NULL; int length = get_size(head); if (position < 1 || position > length) { cout<<"错误的位置参数"<<endl; return head; }
ps:注意使用临时变量保留删除元素的地址,便于在更新链表后对结点进行删除。
类的定义与测试代码
class linknode
{
public:
linknode();
linknode* init_linklist();
linknode* insert(linknode* head, linknode* new_node, int position);
int get_size(linknode* head);
void display(linknode* head);
void set_value(int x);
linknode* del(linknode* head,int position);
private:
int value;
linknode* next;
};
---------------------------------------------------------------
#include <iostream>
#include"linknode.h"
using namespace std;
int main()
{
linknode* a = new linknode;
linknode* b = new linknode;
b->set_value(6);
a = a->init_linklist();
a->display(a);
a = a->insert(a, b, 7);
a->display(a);
a = a->del(a, 3);
a->display(a);
}