11#include <stdio.h>
22#include <stdlib.h>
33
4- struct RandomListNode {
5- int label ;
6- struct RandomListNode * next ;
7- struct RandomListNode * random ;
4+ struct Node {
5+ int val ;
6+ struct Node * next ;
7+ struct Node * random ;
88};
99
10- static struct RandomListNode * copyRandomList (struct RandomListNode * head )
10+ static struct Node * copyRandomList (struct Node * head )
1111{
1212 if (head == NULL ) {
1313 return NULL ;
1414 }
1515
16- struct RandomListNode * p , * new ;
16+ /* copy and redirect next pointer */
17+ struct Node * p , * new ;
1718 for (p = head ; p != NULL ; p = p -> next -> next ) {
1819 new = malloc (sizeof (* new ));
19- new -> label = p -> label ;
20+ new -> val = p -> val ;
2021 new -> next = p -> next ;
2122 p -> next = new ;
2223 }
2324
25+ /* clone random pointer */
2426 for (p = head ; p != NULL ; p = p -> next -> next ) {
2527 new = p -> next ;
2628 new -> random = p -> random != NULL ? p -> random -> next : NULL ;
2729 }
2830
29- struct RandomListNode dummy ;
30- struct RandomListNode * prev = & dummy ;
31+ struct Node dummy ;
32+ struct Node * prev = & dummy ;
3133 for (p = head ; p != NULL ; p = p -> next ) {
3234 new = p -> next ;
3335 p -> next = new -> next ;
36+ /* correct the actual next pointer of the new list */
3437 prev -> next = new ;
3538 prev = new ;
3639 new -> next = NULL ;
@@ -42,10 +45,10 @@ static struct RandomListNode *copyRandomList(struct RandomListNode *head)
4245int main (int argc , char * * argv )
4346{
4447 int i , count = argc - 1 ;
45- struct RandomListNode * head = NULL , * p , * prev ;
48+ struct Node * head = NULL , * p , * prev ;
4649 for (i = 0 ; i < count ; i ++ ) {
4750 p = malloc (sizeof (* p ));
48- p -> label = atoi (argv [i + 1 ]);
51+ p -> val = atoi (argv [i + 1 ]);
4952 p -> next = NULL ;
5053 p -> random = NULL ;
5154 if (head == NULL ) {
@@ -57,26 +60,26 @@ int main(int argc, char **argv)
5760 prev = p ;
5861 }
5962
60- struct RandomListNode * r = head ;
61- struct RandomListNode * q = p = copyRandomList (head );
63+ struct Node * r = head ;
64+ struct Node * q = p = copyRandomList (head );
6265
6366 for (r = head ; r != NULL ; r = r -> next ) {
64- printf ("%d " , r -> label );
67+ printf ("%d " , r -> val );
6568 }
6669 printf ("\n" );
6770
6871 for (r = head ; r != NULL ; r = r -> random ) {
69- printf ("%d " , r -> label );
72+ printf ("%d " , r -> val );
7073 }
7174 printf ("\n" );
7275
7376 for (; p != NULL ; p = p -> next ) {
74- printf ("%d " , p -> label );
77+ printf ("%d " , p -> val );
7578 }
7679 printf ("\n" );
7780
7881 for (; q != NULL ; q = q -> random ) {
79- printf ("%d " , q -> label );
82+ printf ("%d " , q -> val );
8083 }
8184 printf ("\n" );
8285 return 0 ;
0 commit comments