how to copy a linkedlist
2009-03-12 13:16
337 查看
Copy link-list, If You Can
Make a seprate copy of a linked list that has an extra pointer than theregular ones. This pointer points to any randam node in the
list.i.e.::node structure is---
struct node
{
type element
node *next;
node *other;
};
You are provided with head pointer
eg. *other pointer of first node can point to middle node and *other pointer of last node can point to frist node
I need not remind u to keep in mind the complexity..
Holy_Sin
Thursday, June 29, 2006
Deleting … Approving …
Yes, can be done in O(n) time and O(1) space, not counting input and output lists...
Here is come C like code..
// Edge case/error detection missing.
LL * Copy (LL *head){
LL *tmp = head;
LL *prev = NULL;
LL *cur = NULL;
LL *savedNext = NULL;
// Interleave the new and old lists.
while (tmp){
cur = AllocNewLL();
savedNext = tmp->next;
tmp->next = cur;
cur->next = savedNext;
tmp = savedNext;
}
tmp = head;
// Get the correct other pointers for the new list.
while(tmp){
cur = tmp->next;
cur->other = tmp->other->next;
tmp = cur->next;
}
LL * copiedList = head->next;
// Restore the original list.
while (tmp){
cur = tmp->next;
tmp->next = cur->next;
tmp = cur->next;
}
return copiedList;
}
Basically, if original list was A1 -> A2 -> ... -> An
The we make a copy of node Ai. Call that node Bi.
We first make the list look like
A1 -> B1 -> A2 -> B2 -> ... -> An -> Bn (first while loop)
Now
to get the correct other pointer of Bi, we take the other pointer of
Ai, and get the next. i.e say the other of Ai is pointing to Aj. Then
when we follow the next of Aj we get Bj which should be the other of
Bi. (second while loop)
Now we restore the input list back to its form:
A1 -> A2 -> ...-> An. (third while loop)
相关文章推荐
- 如何反转一个单链表 How to reverse a singly linked list
- How to create Linked list using C/C++
- How to use linked list ?
- How to determine whether there are circles in a singly linked list?
- 114. Flatten Binary Tree to Linked List
- When to use LinkedList and When to use ArrayList- An answer in StackOverFlow
- 【leetcode刷题笔记】Flatten Binary Tree to Linked List
- How to Move or Copy a Tablespace to Another Database【每日一译】--2012-11-03
- Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List *
- LeetCode Flatten Binary Tree to Linked List
- LeetCode[Tree]: Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- [LintCode] Flatten Binary Tree to Linked List 将二叉树展开成链表
- How to add elements to a List in Scala
- LeetCode (15) Flatten Binary Tree to Linked List
- How to Get All Product Images in products list page?
- [LeetCode] Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List