一个小时,两道题,都比较简单
1、链表,删除倒数第n个节点
#include<iostream>
#include<fstream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node;
int main()
{
node *head = NULL, *pre = NULL, *cur = NULL, *temp = NULL;
int n, num, count = 0;//n为要删除的倒数第n个节点(从0开始),count为每次输入的链表节点的个数
ifstream cin("data.txt");
while (cin >> n)
{
while (cin >> num) //什么时候没有输入就表示就这些构成链表的节点
{
count++;
if (count == 1) //建立链表头结点
{
head = (node *)malloc(sizeof(node));
head->data = num;
head->next = NULL;
temp = head;
}
else //尾插法
{
cur = (node *)malloc(sizeof(node));
cur->data = num;
cur->next = NULL;
temp->next = cur;
temp = cur;
}
}
int loc = count - n - 1; //从前往后遍历时要删除节点的位置(从0开始)
if (loc == 0) //要删除头结点
head = head->next;
else if (loc >= 5)
cout << "error!" << endl;
else
{
temp = head;
for (int i = 0; i < loc -1; i++)
temp = temp->next;
//此时temp指向要删除的节点的前一个节点
temp->next = temp->next->next;
}
while (head != NULL)
{
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
system("pause");
return 0;
}
2、最长子序列的积(有负数)
#include<iostream>
#include<fstream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
using namespace std;
int MaxSubAry(int num[], int n)
{
int Max = num[0], Pre1 = num[0], Pre2 = num[0], Min = num[0];
for (int i = 1; i < n; i++)
{
Pre1 = max(Pre1*num[i], num[i]);
Pre1 = max(Pre1,Pre2*num[i]);
Pre2 = min(Pre2*num[i], num[i]);
Max = max(Max, Pre1);
}
return Max;
}
int main()
{
int n, num[10], i; //n为个数,num[]存储n个数
ifstream cin("data.txt");
while (cin >> n)
{
for (i = 0; i < n; i++)
cin >> num[i];
int result = MaxSubAry(num, n);
cout << result << endl;
}
system("pause");
return 0;
}