#include <iostream>
using namespace std;
typedef struct Node
{
int m_data;
Node* m_next;
}Node, *List;
bool insertList(List& list, int index, int e)
{
Node* p = list;
int cur_index = -1;
// p指向要插入的位置的前一个结点,只需要保证p不为NULL就好了,不需要保证下一个结点不为NULL
while (p && cur_index < index-1)
{
p = p->m_next;
++cur_index;
}
if (p)
{
Node* node = new Node;
node->m_data = e;
node->m_next = p->m_next;
p->m_next = node;
return true;
}
return false;
}
bool deleteList(List& list, int index, int& e)
{
Node* p = list;
int cur_index = -1;
// p指向要删除结点的前一个结点,但是必须保证p->m_next都不为空,因为等下p->m_next要被释放掉
if (p->m_next && cur_index<index-1)
{
p = p->m_next;
++cur_index;
}
if (p->m_next)
{
Node* temp = p->m_next;
p->m_next = temp->m_next;
e = temp->m_data;
delete temp;
temp = 0;
return true;
}
return false;
}
void CreateList()
{
Node* list = new Node;
list->m_next = 0;
int data[4] = {1,2,3};
for (int index = 0; index < 3; ++index)
{
insertList(list, index, data[index]);
}
}
int main()
{
CreateList();
return 0;
}
数据结构之链表
最新推荐文章于 2023-08-20 16:00:00 发布