+ Reply to Thread
Results 1 to 2 of 2

Thread: Copy List with random pointer

  1. #1
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321

    Copy List with random pointer

    Write code to create a copy of a linked list with two pointers, one pointing to the next node and another one to any random node of the List.

  2. #2
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321
    Code:
    struct linkedList {
    	int data;
    	struct linkedList* next;
    	struct linkedList* random;
    };
    
    typedef struct linkedList* List;
    
    // Not for this list structure
    List randomCopy(List L)
    {
    	List p,q,r;
    	if(L == NULL)
    		return NULL;
    	
    	for(p=L; p != NULL; p = p->next->next) {
    		q = (List) malloc(sizeof(struct linkedList));
    		q->data = p->data;
    		q->next = p->next;
    		p->next = q;
    	}
    	for(p=L; p != NULL; p = p->next->next) {
    		p->next->random = q->random->next;
    	}
    	q = r = L->next;
    	for(p = L; p! = NULL; p = p->next) {
    		p->next = p->next->next;
    		q->next = q->next->next;
    		q = q->next;
    	}
    	return r;
    }

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 1
    Last Post: 29th May 2010, 12:35
  2. Stack Pointer vs Frame Pointer
    By Surfer in forum Samsung
    Replies: 0
    Last Post: 26th May 2010, 23:47
  3. Replies: 2
    Last Post: 30th March 2010, 16:59
  4. Create Copy of a BST
    By TopGun in forum Algorithm/Data Structure Questions
    Replies: 1
    Last Post: 2nd June 2008, 15:56

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts