L2-002. 链表去重(模拟)

xiaoxiao2021-02-28  21

【题目链接】 https://www.patest.cn/contests/gplt/L2-002

题目意思

给一段链表,去除绝对值相同的节点,把去除的节点重新组成一条链表。

解题思路

没规定内存,地址也在10^6内直接用数组模拟就可以了,注意下输出,可能没有删除的节点也就没有第二条链表。

代码部分

#include <iostream> #include <stdio.h> #include <string.h> #include <queue> #include <algorithm> #include <math.h> using namespace std; const int maxn=100005; int vis[maxn]; struct node { int key; int next; } a[maxn],c[maxn],b[maxn]; int main() { int h1,h2,n; memset(vis,0,sizeof(vis)); scanf("%d %d",&h1,&n); for (int i=0; i<n; i++) { int q,w,e; scanf("%d %d %d",&q,&w,&e); a[q].key=w; a[q].next=e; } int next=h1,j=0,k=0; while (1) { if (next==-1) break; if (!vis[abs(a[next].key)]) { if (j==0) { c[j].key=a[next].key; } else { c[j].key=a[next].key; c[j-1].next=next; } j++; vis[abs(a[next].key)]++; } else { if (k==0) { h2=next; b[k].key=a[next].key; } else { b[k].key=a[next].key; b[k-1].next=next; } k++; } next=a[next].next; } b[k-1].next=-1; c[j-1].next=-1; printf("d ",h1); for (int i=0; i<j-1; i++) { printf("%d d\n",c[i].key,c[i].next); if (i!=j-1) printf("d ",c[i].next); } printf("%d %d\n",c[j-1].key,c[j-1].next); if (k!=0) { printf("d ",h2); for (int i=0; i<k-1; i++) { printf("%d d\n",b[i].key,b[i].next); if (i!=k-1) printf("d ",b[i].next); } printf("%d %d\n",b[k-1].key,b[k-1].next); } return 0; }
转载请注明原文地址: https://www.6miu.com/read-1700228.html

最新回复(0)