首先:
思想1:暴力求解
typedef struct Node node;
int test( node* phead,int k )
{
int z = 0;
node* pf = phead;
while( k )
{
pf = pf->next;
k--;
}
while( pf->random != phead )
{
z++;
phead = phead->next;
}
return z;
}
void contect(node* head1,int k,int i)
{
node* a = head1;
node* p = head1;
while( k )
{
a = a->next;
k--;
}
while( i )
{
p = p->next;
i--;
}
a->random = p;
}
struct Node* copyRandomList(struct Node* head) {
node* pf = NULL;
int i = 0;
int k = 0;
node* phead = head;
node* head1 = NULL;
node* tail = NULL;
while( head )
{
pf = (node*)malloc(sizeof(node));
pf->val = head->val;
pf->next = NULL;
if( head1 == NULL )
{
head1 = pf;
}
else
{
tail->next = pf;
}
tail = pf;
head = head->next;
}
node* g = head1;
while( head1 )
{
i = test(phead,k);
contect(g,k,i);
k++;
head1 = head1->next;
}
return g;
}
思想2:在原链表的每一个节点后,插入一个一样的节点,对插入后的节点的random指针赋值
在拆开节点,组成新的链表。
typedef struct Node Node;
struct Node* copyRandomList(struct Node* head) {
Node* phead = head;
Node* pf = NULL;
Node* a = NULL;
Node* copy = NULL;
int i = 0;
while( head )
{
pf = (Node*)malloc(sizeof(Node));
if( i == 0 )
{
copy = pf;
i++;
}
a = head->next;
head->next = pf;
pf->next = a;
pf->val = head->val;
head = a;
}
head = phead;
while( head )
{
if( head->random == NULL )
{
head->next->random = head->random;
head = head->next->next;
}
else
{
head->next->random = head->random->next;
head = head->next->next;
}
}
head = phead;
while( head )
{
a = head->next->next;
if(a)
head->next->next = a->next;
head->next = a;
head = a;
}
return copy;
}