如何用 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