让我们首先定义包含数据和指向下一个节点的指针的链表。
struct Node { int data; struct Node* next; };
接下来我们创建我们的createNode(int data)函数,该函数将 int 数据作为参数,并在分配参数值后返回新创建的节点。指向该节点的下一个指针将为空。
Node* createNode(int data){ struct Node* newNode = new Node; newNode->data = data; newNode->next = NULL; return newNode; }
现在我们有我们的 deleteMiddle(struct Node* head) 函数,它接受根节点。如果根节点不为空,则它只是将中间值之前的节点的下一个值分配给中间值旁边的节点,并返回临时头,即修改后的头。
struct Node* deleteMiddle(struct Node* head){ if (head == NULL) return NULL; if (head->next == NULL) { delete head; return NULL; } Node* temphead = head; int count = nodeCount(head); int mid = count / 2; while (mid-- > 1) { head = head->next; } head->next = head->next->next; return temphead; }
最后我们有我们的 printList(Node *ptr) 函数,它获取列表头并打印列表。
void printList(Node * ptr){ while (ptr!= NULL) { cout << ptr->data << "->"; ptr = ptr->next; } cout << "NULL"<<endl; }
让我们看看下面删除单链表中间的实现。
#include <iostream> using namespace std; struct Node { int data; struct Node* next; }; Node* createNode(int data){ struct Node* newNode = new Node; newNode->data = data; newNode->next = NULL; return newNode; } int nodeCount(struct Node* head){ int count = 0; while (head != NULL) { head = head->next; count++; } return count; } struct Node* deleteMiddle(struct Node* head){ if (head == NULL) return NULL; if (head->next == NULL) { delete head; return NULL; } Node* temphead = head; int count = nodeCount(head); int mid = count / 2; while (mid-- > 1) { head = head->next; } head->next = head->next->next; return temphead; } void printList(Node * ptr){ while (ptr!= NULL) { cout << ptr->data << "->"; ptr = ptr->next; } cout << "NULL"<<endl; } int main(){ struct Node* head = createNode(2); head->next = createNode(4); head->next->next = createNode(6); head->next->next->next = createNode(8); head->next->next->next->next = createNode(10); cout << "Original linked list"<<endl; printList(head); head = deleteMiddle(head); cout<<endl; cout << "After deleting the middle of the linked list"<<endl; printList(head); return 0; }
输出结果
上面的代码将产生以下输出 -
Original linked list 2->4->6->8->10->NULL After deleting the middle of the linked list 2->4->8->10->NULL