链表的储存不连续,通过Node结点的指针指向下一个成员。
一些操作:
翻转>创建一个新结点,遍历拷贝头插。
删除特定值>使用前驱结点cur->next->value查找进行删除。
记得有结点被删除要free();
c版本单向链表
#include<memory>
#include<assert.h>
typedef size_t DataType;
//声明一个结点
typedef struct ListNode{
ListNode * next;
DataType value;
}Node;
//一个链表只用保存头结点的地址
typedef struct SList{
Node* first;
}SList;
SList* InitList(SList* s)
{
s->first = NULL;
return s;
}
//头插
SList* PushFront(SList* s, DataType val)
{
Node * node = (Node*)malloc(sizeof(DataType));
node->value = val;
node->next = s->first;
s->first = node;
return s;
}
//尾插
SList* PushBack(SList* s, DataType val)
{
Node* node = (Node*)malloc(sizeof(DataType));
node->value = val;
node->next = NULL;
if (s->first == NULL)
{
s->first = node;
}
else
{
Node* cur = s->first;
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = node;
}
return s;
}
//头删
void PopFront(SList* s)
{
assert(s != NULL);
assert(s->first != NULL);
Node* cur = s->first->next;
free(s->first);
s->first = cur;
return;
}
//尾删
void PopBack(SList* s)
{
assert(s != NULL);
assert(s->first != NULL);
Node* cur = s->first;
if (s->first->next == NULL)
{
free(s->first);
s->first = NULL;
return;
}
while (cur->next->next != NULL)
{
cur = cur->next;
}
free(cur->next);
cur->next = NULL;
return;
}
int main()
{
SList list;
InitList(&list);
PushFront(&list, 4);
PushFront(&list, 5);
PushFront(&list, 7);
PushBack(&list, 8);
PushBack(&list, 10);
// PopFront(&list);
// PopBack(&list);
return 0;
}
C++版本双向链表
class Node {
public:
Node* _previous;
Node* _next;
int _data;
};
class List {
public:
List(int length) :
_length(length),
_head(new Node),
_tail(new Node)
{
_head->_previous = nullptr;
_head->_next=_tail;
_tail->_previous = _head;
_tail->_next = nullptr;
_head->_data = 0;
Node* temp(new Node);
temp = _head;
for (int i=0; i < _length; ++i)
{
Node* cur(new Node);
temp->_next = cur;
cur->_previous = temp;
cur->_data = i+10;
temp = cur;
temp->_next = nullptr;
_tail = temp;
}
}
void print()
{
for (Node* temp = _head->_next; temp != nullptr; temp = temp->_next)
{
cout << temp->_data << " ";
}
cout << endl;
}
void push_back(int number)
{
Node* cur(new Node);
cur->_data = number;
cur->_previous = _tail;
_tail->_next = cur;
cur->_next = nullptr;
}
void delet(Node* node)
{
Node* temp=node->_previous;
temp->_next = node->_next;
node->_next->_previous = temp;
delete node;
}
public:
Node* _head;
Node* _tail;
int _length;
};
void testNode()
{
List list(8);
Node* node3 = list._head->_next->_next->_next;
list.delet(node3);
list.print();
list.push_back(20);
list.print();
}
int main()
{
testNode();
return 0;
}```