如何用 C++ 删除链表中间部分?
首先,让我们定义我们的链表,其中包含数据和指向下一个节点的指针。
struct Node {
int data;
struct Node* next;
};接下来,我们创建 createNode(int data) 函数,它接受 int data 作为参数,并在分配参数值后返回新增的节点。指向节点的下一个指针将为 null。
Node* createNode(int data){
struct Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}现在,我们有了 deleteMiddle(struct Node* head) 函数,它采用根节点。如果根节点不为 null,则它只是将中间值之前节点的下一个值分配给中间值之后的节点,并返回修改后的头 temphead。
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP