本文主要是介绍【LeetCode】203. Remove Linked List Elements,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//LeetCode 203. 删除链表中的元素
#include "stdafx.h"
#include <iostream>
using namespace std;typedef int ElemType;
struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}
};class Solution {
public:ListNode* removeElements(ListNode* head, int val) {if (head == NULL) return NULL;ListNode *next = removeElements(head->next, val);if (head->val == val) return next;else{head->next = next;return head;}}//创建无头结点的单链表ListNode* Create(void){char s;ListNode *tail = NULL;ListNode *head = NULL;while (1){ListNode *tmp = new ListNode(0); //定义一个s节点用来存放每次要输入的值scanf("%d", &tmp->val);if (head == NULL){head = tmp;}else{tail->next = tmp;}tail = tmp;s = getchar();if (s == '\n') { break; }}if (tail != NULL)tail->next = NULL;return head;}//输出无头结点单链表void List(ListNode *L){ListNode *p;p = L; //while (p != NULL){printf("%2d", p->val);p = p->next;}}
};int main()
{ListNode *L1;int temp;printf("请输入链表:\n");L1 = Solution().Create();printf("\n请输入要移除的元素:\n");scanf("%d", &temp);ListNode* ret = Solution().removeElements(L1, temp);printf("移除后的链表为:\n");Solution().List(L1);system("pause");return 0;
}
这篇关于【LeetCode】203. Remove Linked List Elements的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!