#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*问题:Remove all elements from a linked list of integers that have value val.ExampleGiven: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6Return: 1 --> 2 --> 3 --> 4 --> 5分析:删除链表中等于指定元素的所有结点。关键删除结点的时候考虑在头结点1】待删除的结点在头结点,令之后的结点成为头结点需要记录当前结点的前一个结点,后一个结点,删除当前结点后,令前一个结点指向后一个结点,并令当前结点为后一个结点输入:7(结点个数) 6(待删除元素)1 2 6 3 4 5 62 11 13 11 1 23 12 1 1输出:1 2 3 4 5no result22*/ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };class Solution {public: ListNode* removeElements(ListNode* head, int val) { //头结点为空,直接返回NULL if(!head) { return NULL; } ListNode* PRevious = NULL; ListNode* next = NULL; ListNode* node = head; ListNode* newHead = head; while(node) { next = node->next; //如果当前结点是待删除结点 if(val == node->val) { //如果待删除结点的前一个结点存在,那么就重新设定指向 if(previous) { previous->next = next; delete node; } //如果待删除的结点是头结点,直接删除该结点,并令next结点成为头结点 else { newHead = next; delete node; } node = next; } //当前结点不是待删除结点,更新结点 else { previous = node; node = next; } } return newHead; }};void print(ListNode* head){ if(!head) { cout << "no result" << endl; } ListNode* tempHead = head; while(head) { cout << head->val << " "; head = head->next; } cout << endl; head = tempHead;}ListNode* buildList(vector<int>& nums){ if(nums.empty()) { return NULL; } int size = nums.size(); ListNode* head ; ListNode *tail; ListNode* node; for(int i = 0 ; i < size ; i++) { if(i) { node = new ListNode(nums.at(i)); tail->next = node; tail = node; } else { head = new ListNode(nums.at(i)); tail = head; } } return head;}void deleteList(ListNode* head){ ListNode* node; while(head) { node = head->next; delete head; head = node; }}void process(){ vector<int> nums; int value; int num; Solution solution; vector<int> result; int delValue; while(cin >> num >> delValue ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } ListNode* head = buildList(nums); ListNode* newHead = solution.removeElements(head , delValue); print(newHead); deleteList(newHead);//删除节点了 }}int main(int argc , char* argv[]){ process(); getchar(); return 0;}
新闻热点
疑难解答