64,644
社区成员
发帖
与我相关
我的任务
分享
//创建的链表,剩下移动不会了,求解
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int N = 5;
struct Node
{
int data;
Node *next;
};
int main()
{
srand ( time ( 0 ) );
int i;
Node *head, *p;
head = new Node;
int a[5]={6,14,2,5,6};
for ( i = 0, p = head; i < N; i++ )
{
p->next = new Node;
p = p->next;
p->next = nullptr;
p->data = a[i];
}
p = head->next;
while ( p )
{
cout << &(p->data) << "\t";
p = p->next;
}
cout << endl;
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int N = 5;
struct Node
{
int data;
Node *next;
};
int _tmain(int argc, _TCHAR* argv[])
{
int i;
Node *head, *p;
head = new Node;
int a[5]={6,14,2,14,6};
for ( i = 0, p = head; i < N; i++ )
{
p->next = new Node;
p = p->next;
p->next = NULL;
p->data = a[i];
}
p = head->next;
while ( p )
{
cout << &(p->data) << "\t";
p = p->next;
}
cout << endl;
// 查找最大值
Node* max;
int flag = 0; //相同最大值数量
int maxValue = 1<<(sizeof(int)*8-1);
for(p = head->next; p != NULL; p = p->next)
{
if(p->data > maxValue)
{
max = p;
maxValue = p->data;
flag = 1;
}
else if(p->data == maxValue)
{
max = p;
flag++;
}
}
// 删除最大值(如果存在相同最大值的情况,删除前面所有相同的,保留最后一个最大值)
for(p = head; p->next != NULL; p = p->next)
{
if(p->next->data == maxValue)
{
Node* tmp = p->next;
p->next = p->next->next;
if(flag > 1)
{
delete tmp;
flag--;
}
}
}
if(p->next == NULL)
p->next = max; // 最后的位置放上最大值
max->next = NULL;
//
p = head->next;
while ( p )
{
cout << &(p->data) << "\t";
p = p->next;
}
cout << endl;
// 退出程序前,将链表中所有节点释放(切记,自己New的内存,一定要释放)
p = head;
while ( p )
{
Node* tmp = p;
p = p->next;
delete tmp;
tmp = NULL;
}
return 0;
}
void move_max(std::vector<node*>& v)
{
int last = v.size() - 1;
int max = 0;
for (int i =0; i<last;i++)
{
if (v[i]->data < v[i + 1]->data)
{
max = i + 1;
}
}
auto tmp = v[last];
v[last] = v[max];
v[max] = tmp;
}
没测试,自己改下测试