单链表删nodes

来源:互联网 发布:ar软件 编辑:程序博客网 时间:2024/05/17 03:37
///////////////////////////////////////////////////// C++ /////////////////////////////////////////////#include <iostream>#include <stdio.h>using namespace std;struct ListNode{int val;ListNode*next;};ListNode *removeNode(ListNode *firstNode, int removalRequests[], int removalRequests_Length){if (firstNode == nullptr)return firstNode;// dummy nodeListNode dummy{ -1, firstNode};// position node pointerListNode *current = firstNode;// previous node pointerListNode *previous = &dummy;// index for removal Requests arrayint index = 0;for (int count = 0; current != nullptr && index < removalRequests_Length; count++){// if match delete position nodeif (removalRequests[index] == count){// update indexindex++;// change the previous node next pointer to// next pointer of the node to be deleted.previous->next = current->next;free(current);current = previous->next;}else{previous = current;current = current->next;}}return dummy.next;}int main(){ListNode *head = new ListNode();head->val = 1;ListNode *q = head;ListNode *p = nullptr;for (int i = 2; i <= 10; i++) {p = new ListNode();p->val = i;q->next = p;q = q->next;p->next = nullptr;p = head;}cout << "目标链表:" << endl;while (p != NULL) {cout << p->val << " ";p = p->next;}cout << endl;int foo[2] = {1,3};ListNode *x = removeNode(head, foo, 2);cout << "结果链表:" << endl;while (x != NULL) {cout << x->val << " ";x = x->next;}cout << endl;}

0 0
原创粉丝点击