【C++】删除节点

1、已知当前节点P2,删除该节点。

在这里插入图片描述

#include<iostream>
using namespace std;
struct ListNode {
    
    
    char val;
    ListNode* next;
    ListNode(){
    
    }
    ListNode(char x) : val(x), next(NULL) {
    
    }
    
};
void print(ListNode* pHead) {
    
    
    ListNode* p = pHead->next;
    while (p != NULL) {
    
    
        cout << p->val << " ";
        p = p->next;
    }
}
int  main() {
    
    
    ListNode* pHead = new ListNode;

    ListNode* P0 = new ListNode('a');
    pHead->next = P0;

    ListNode* P1 = new ListNode('b');
    P0->next = P1;

    ListNode* P2 = new ListNode('c');
    P1->next = P2;

    ListNode* P3 = new ListNode('d');
    P2->next = P3;

    ListNode* P4 = new ListNode('e');
    P3->next = P4;

    ListNode* P5 = new ListNode('f');
    P4->next = P5;
    cout <<"P2的值:"<< P2 << "\n";
    //ListNode* p = P2;
    //P2 = P2->next;
    //delete p;
    cout << "P2的值:" << P2 << "\n";
    cout << "P1->next的值:"<<P1->next << "\n";

    //正确代码
    ListNode* p = P2->next;
    P2->val = p->val;
    P2->next = p->next;
    delete p;
    print(pHead);

	return 0;
}

在这里插入图片描述

2、已知节点P1,删除下一节点P2。

在这里插入图片描述

#include<iostream>
using namespace std;
struct ListNode {
    
    
    char val;
    ListNode* next;
    ListNode(){
    
    }
    ListNode(char x) : val(x), next(NULL) {
    
    }
    
};
void print(ListNode* pHead) {
    
    
    ListNode* p = pHead->next;
    while (p != NULL) {
    
    
        cout << p->val << " ";
        p = p->next;
    }
}
int  main() {
    
    
    ListNode* pHead = new ListNode;

    ListNode* P0 = new ListNode('a');
    pHead->next = P0;

    ListNode* P1 = new ListNode('b');
    P0->next = P1;

    ListNode* P2 = new ListNode('c');
    P1->next = P2;

    ListNode* P3 = new ListNode('d');
    P2->next = P3;

    ListNode* P4 = new ListNode('e');
    P3->next = P4;

    ListNode* P5 = new ListNode('f');
    P4->next = P5;
    
    ListNode* p = P1->next;
    P1->next = p->next;
    delete p;
    print(pHead);

	return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_48180029/article/details/113802225
今日推荐