移除序列指定位置元素(链表)
时间限制: 1S类别: DS:数组与链表->链表–简单
晚于: 2022-03-17 23:55:00后提交分数乘系数50%
截止日期: 2022-03-20 23:55:00
问题描述 :
使用带头结点的单链表编程:
一群学生排成一行,输入一个位置,将该位置的学生移除。
第一个学生的位置为1,第n个学生的位置为n。
输入说明 :
第一行输入学生信息:
第一个整数n(0<=n<=100),表示共有n个学生,其后有n个整数,表示n个学生的学号
第二行及以后各行,每行输入一个整数,表示要移除的学生位置。
输出说明 :
每次移除一个学生后,在一行里输出完整的学号序列,以head开头,以tail结尾,学号之间以“–>”分隔(参见范例)。
如果需要移除学生的位置不合法,则输出“invalid”(不包括双引号)
输入范例 :
3 4 5 10
10
3
0
2
1
输出范例 :
invalid
head–>4–>5–>tail
invalid
head–>4–>tail
head–>tail
#include <iostream>
#include <cstring>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <sstream>
#include <vector>
#include <cstdio>
#define endl '\n'
using namespace std;
int ok = 0;
struct code
{
code* next;
int data;
code() : data(0), next(NULL) {}
code(int x) : data(x), next(NULL) {}
code(int x, code* next) : data(x), next(next) {}
};
code* creatlist()
{
code* head ;
head = new code();
code* p1=0, *p2=0;
int n=0, num;
int len; cin >> len;
while (n < len && cin >> num)
{
p1 = new code(num);
n += 1;
if (n == 1)
head->next = p1;
else
p2->next = p1;
p2 = p1;
}
ok = len;
return head;
}
code* shortlist(int n,code *head)
{
code* p = head;
n -= 1; int nn = n;
while (n--)
{
p = p->next;
}
code* q = p->next;
if (ok != 1&&ok!=nn)
{
p->next = p->next->next;
}
else if (ok==1)
head = NULL;
else if (nn==ok)
delete q;
ok--;
return head;
}
int main ()
{
code* p = creatlist();
int n;
if (ok == 0)
while (cin >> n)
cout << "invalid" << endl;
while (cin>>n)
{
if (n > ok || n <= 0)
{
cout << "invalid" << endl;
}
else
{
p = shortlist(n, p);
if (ok != 0)
{
code* q = p->next;
cout << "head-->";
for (int i = 0; i < ok; i++)
{
cout << q->data << "-->";
q = q->next;
}
cout << "tail" << endl;
}
else
{
cout << "head-->tail" << endl;
}
}
}
return 0;
}