15
作者:
xxdmd8
,
2024-12-20 09:15:37
,
所有人可见
,
阅读 5
DGH-DS-单链表结点的删除与排序
【问题描述】输入一组整数,以单链表的形式存储,删掉里面存放偶数的节点,并按照从小到大的顺序排序,并输出
【输入形式】整数序列,以空格为间隔,最多十个整数
【输出形式】整数序列,以空格为间隔
【样例输入】3 5 8 9 1 2 4
【样例输出】1 3 5 9
#include<iostream>
#include <vector>
#include<algorithm>
using namespace std;
struct ListNode{
int val;
ListNode* next;
};
typedef ListNode* LinkList;
LinkList createListFromArray(vector<int>& arr){
LinkList L = new ListNode{0,nullptr};
ListNode* r = L;
for(int val:arr){
r->next = new ListNode{val,nullptr};
r = r->next;
}
return L;
}
void printList(LinkList L){
ListNode* p = L->next;
while(p){
cout << p->val << " ";
p = p->next;
}
}
void deleteList(LinkList& L){
ListNode* p = L->next;
while(p){
ListNode* s = p;
p = p->next;
delete s;
}
delete L;
}
void deleteEvenNodes(LinkList L){
ListNode* pre = L;
ListNode* cur = L->next;
while(cur){
if(cur->val % 2 == 0){
pre->next = cur->next;
delete cur;
cur = pre->next;
}else{
pre = cur;
cur = cur->next;
}
}
}
vector<int> getValsFromList(LinkList L){
vector<int> vals;
ListNode* p = L->next;
while(p){
vals.push_back(p->val);
p = p->next;
}
return vals;
}
LinkList createSortedListFromArray(vector<int>& arr){
vector<int> sortedArr = arr;
sort(sortedArr.begin(),sortedArr.end());
return createListFromArray(sortedArr);
}
int main(){
vector<int> arr;
int temp;
while(cin >> temp){
arr.push_back(temp);
if(cin.peek() == '\n') break;
}
LinkList L1 = createListFromArray(arr);
//printList(L1);
deleteEvenNodes(L1);
arr = getValsFromList(L1);
LinkList L2 = createSortedListFromArray(arr);//= createListFromArray(arr);
printList(L2);
deleteList(L1),deleteList(L2);
return 0;
}