标签:双向链表 tail for 实现 ini class 单链表 ali ==
设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val
和 next
。val
是当前节点的值,next
是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev
以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。
在链表类中实现这些功能:
index
个节点的值。如果索引无效,则返回-1
。val
的节点。插入后,新节点将成为链表的第一个节点。val
的节点追加到链表的最后一个元素。index
个节点之前添加值为 val
的节点。如果 index
等于链表的长度,则该节点将附加到链表的末尾。如果 index
大于链表长度,则不会插入节点。如果index
小于0,则在头部插入节点。index
有效,则删除链表中的第 index
个节点。
struct Node { int val; Node *next, *prev; Node(int x): val(x), next(nullptr), prev(nullptr){}; }; class MyLinkedList { public: /** Initialize your data structure here. */ int len; Node *head, *tail; MyLinkedList() { len = 0; head = nullptr; tail = nullptr; } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ int get(int index) { if(index < 0 || len == 0 || index >= len) return -1; else{ Node *p = head; for(int i = 0; i < index; i++){ p = p->next; } return p->val; } } /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ void addAtHead(int val) { Node *new_Node = new Node(val); if(head == nullptr){ head = new_Node; tail = new_Node; } else{ new_Node->next = head; head->prev = new_Node; head = new_Node; } len++; } /** Append a node of value val to the last element of the linked list. */ void addAtTail(int val) { Node *new_Node = new Node(val); if(head == nullptr){ head = new_Node; tail = new_Node; } else{ new_Node->prev = tail; tail->next = new_Node; tail = new_Node; } len++; } /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ void addAtIndex(int index, int val) { Node *new_Node = new Node(val); if(index == len){ addAtTail(val); } else if(index <= 0){ addAtHead(val); } else { Node *p = head; for(int i = 1; i < index; i++){ p = p->next; } new_Node->next = p->next; new_Node->prev = p; p->next->prev = new_Node; p->next = new_Node; len++; } } /** Delete the index-th node in the linked list, if the index is valid. */ void deleteAtIndex(int index) { if(head == nullptr || index >= len || index < 0){ return; } else{ if(index == 0){ if(len == 1){ head = nullptr; tail = nullptr; } else{ head = head->next; head->prev->next = nullptr; head->prev = nullptr; } } else if(index == len-1){ tail = tail->prev; tail->next->prev = nullptr; tail->next = nullptr; } else{ Node *p = head; for(int i = 0; i < index; i++){ p = p->next; } p->next->prev = p->prev; p->prev->next = p->next; p->prev = nullptr; p->next = nullptr; } len--; } } };
标签:双向链表 tail for 实现 ini class 单链表 ali ==
原文地址:https://www.cnblogs.com/olajennings/p/12466875.html