GPLT L2-002. 链表去重【链表】

题目:链表去重

思路:

(1)直接用数组模拟链表即可;

(2)利用一个标记数组,将加入去重链表的值进行绝对值标记。

代码:

#include 
#include 
#include 
using namespace std;
const int maxn = 100005;
int visit[maxn];
struct link{
    int key;//值
    int next;//下一结点
}a[maxn];
link ans[maxn],del[maxn];
int oper(int start){
    int recA=maxn-3,recD=maxn-3,recS=maxn-3,flag = 1;
    while(1){
        if(!visit[abs(a[start].key)]){//如果当前链表中没有此值,进行链接
            visit[abs(a[start].key)] = 1;//标记链表存在此值了
            ans[recA].next = start;//将上一结点的下一结点存为当前结点,意思是将当前结点链到上一结点上
            ans[start].key = a[start].key;//将当前结点的值保存
            ans[start].next = -1;//当前结点的下一结点置为尾结点-1
            recA = start;//记录当前结点
        }else{//出现重复元素
            if(flag) {recS = start;flag = 0;}//记录首结点
            //记录删除链表的链接同上
            del[recD].next = start;
            del[start].key = a[start].key;
            del[start].next = -1;
            recD = start;
        }
        if(a[start].next == -1) break;//当达到尾结点时结束
        start = a[start].next;//下一结点
    }
    return recS;//返回删除链表的首结点
}
void print(link p[],int start){//输出链表元素
    while(p[start].next != -1){
        printf("%05d %d %05d\n",start,p[start].key,p[start].next);
        start = p[start].next;
    }
    printf("%05d %d -1\n",start,p[start].key);
}
int main()
{
    int n,start,add,key,nex;
    while(~scanf("%d%d",&start,&n)){
        memset(visit,0,sizeof(visit));
        for(int i=0;i



你可能感兴趣的:(---数据结构---,链表,GPLT,天梯赛)