GK
BAN USERO(N), Idea: let's use data structure which avoids duplicates - hashset
public static Integer[] removeDuplicates1(Integer[] arr){
HashSet<Integer> set = new HashSet<>();
for (Integer elem : arr){
set.add(elem);
}
Integer[] answer = new Integer[set.size()];
set.toArray(answer);
return answer;
}
O(NlogN), Idea: let's sort input and place all unique elements in the beggining
public static Integer[] removeDuplicates2(Integer[] arr){
if (arr.length == 0){
return new Integer[0];
}
Arrays.sort(arr);
int lastNonRepeated = 0;
for (int i = 1; i < arr.length; i++){
if (arr[i] == arr[lastNonRepeated]){
continue;
}
arr[++lastNonRepeated] = arr[i];
}
Integer[] answer = new Integer[lastNonRepeated+1];
for (int i = 0; i <= lastNonRepeated; i++){
answer[i] = arr[i];
}
return answer;
}
public static List<Node> toLists(Node root){
ArrayList<Node> result = new ArrayList<>();
LinkedList<Node> previousLayer = new LinkedList<>();
if (root != null) {
previousLayer.add(root);
}
while(previousLayer.size() != 0){
LinkedList<Node> currentLayer = new LinkedList<>();
for (Node node : previousLayer){
if (node.left != null){
currentLayer.add(node.left);
}
if (node.right != null){
currentLayer.add(node.right);
}
}
result.add(layerToList(previousLayer));
previousLayer = currentLayer;
}
return result;
}
private static Node layerToList(List<Node> layer){
Node currentHead = null, current = null;
for (Node node : layer){
node.left = null;
node.right = null;
if (currentHead == null){
currentHead = node;
current = node;
}
else{
current.right = node;
current = current.right;
}
}
return currentHead;
}
To Naomi: I'm glad I was able to help you! :) I failed interview at Yandex only because of a dirty coding. So, don't repeat my mistakes :) I think there is no appropriate books describing how to write well-readable code, though I would highly recommend you to take a look at trending github projects.
To Michael: You caught me! :) Edited
To Rams: If I correctly understood your question - we always need to check if head is less than tail, because we need to guarantee that charAt operation works with correct indices (they are positive and less that str.length()) F.e. for input "#!!#" if we won't check for "h < t", soon the head index will reach the end of the string and will get an Exception.
Because of it, both while loops contains this condition. It works correctly for input "A!#A".
Your implementation is correct, but quality of the code can be better :) :
1) You may use Character.isLetterOrDigit(char c)
2) In the end of the functions you shouldn't check whether the boolean variable/result is true or false.
if(valid)
return true;
else
return false;
should be replaced with
return valid;
Same story with isLetterDigit implementation - should be replaced with
public static boolean isLetterDigit(char ch)
{
return (Character.isLetter(ch)||Character.isDigit(ch));
}
public static boolean isPalindrome(String str){
if (str == null){
return true;
}
for (int head = 0 , tail = str.length() -1 ; head < tail; head++, tail--){
while(!Character.isLetterOrDigit(str.charAt(head)) && head < tail){
head++;
}
while(!Character.isLetterOrDigit(str.charAt(tail)) && head < tail){
tail--;
}
if (Character.toLowerCase(str.charAt(tail)) != Character.toLowerCase(str.charAt(head))){
return false;
}
}
return true;
}
Base: Create two pointers p1 and p2. Move p2 N nodes forward. ( handle situation if there are less than N nodes in list)
Step: each time save p2 into pointer p3 and try to move p2 N nodes forward.
If success, set p1 = p3 and repeat step.
If not - we moved p2 k times (k<N) and reached the end, so move p1 k times forward. node(p1) will be the answer because before this step there were N nodes between p1 and p2.
select indexes of characters we can move. generate all permutations of them. replace chars in the original string for each permutation.
Example:
input: q1eRz
arr: [0,2,4]
possible permutations:
[0,4,2] -> q1zRe
[2,0,4] -> e1qRz
[2,4,0] -> r1zRq
etc...
if you have dictionary check if the anagram is presented in it.
Explanation:
First of all we need to find the smallest substring from 0 to i that contains all necessary elements. It's the first answer, but we may try to improve it (find shorter substring). Let's put tail = 0 and head = i. Then iteratively increase head index and each time we check if we can cut tail: we can do it, if charAt(tail) presented more than one time in substring(tail,head) or it's not presented in set of chars. Each time we cut the tail, check if the length of the new substring is smaller and if it is - remember answer.
private static String getSubstring(String str , HashSet<Character> chars){
int head_ans = -1;
int tail_ans = -1;
int length = Integer.MAX_VALUE;
int head = 0;
HashMap<Character, Integer> charCount = new HashMap<>();
for (int tail = 0; tail < str.length(); tail++){
char currChar = str.charAt(tail);
if (!chars.contains(currChar)){
continue;
}
charCount.put(currChar , charCount.containsKey(currChar) ? charCount.get(currChar) + 1 : 1);
while(true){
char headChar = str.charAt(head);
if (!chars.contains(headChar)){
head++;
continue;
}
int headCharCount = charCount.get(headChar);
if (headCharCount == 1) {
break;
}
head++;
charCount.put(headChar , headCharCount - 1);
}
if (charCount.size() == chars.size() && (tail - head + 1) < length){
tail_ans = tail;
head_ans = head;
length = tail-head+1;
}
}
return (tail_ans != -1) ? str.substring(head_ans , tail_ans+1) : "";
}
In general the given graph is unweighted, because the cost of each edge is 1. So we have to solve the problem of shortests path.
It's not clear for me from task's description how are we gonna send packets: "any to any" or "specific to any".
For "specific to any" case it can be solved with BFS with remembering of previous vertex in the best path for each vertex. I think that you may perform the same idea for "any to any".
You also may use Bellman–Ford or Dijkstra algorithm.
public static void print4Sum(int[] arr){
getSums(arr).values().forEach((x) -> printAllCombinations(x));
}
private static void printAllCombinations(List<Pair<Integer,Integer>> list){
for (int i = 0; i < list.size() - 1; i++){
Pair<Integer,Integer> p1 = list.get(i);
for (int j = i+1 ; j < list.size(); j++){
Pair<Integer,Integer> p2 = list.get(j);
System.out.printf("(%d,%d,%d,%d)\r\n",p1.getKey(),p1.getValue(),p2.getKey(),p2.getValue());
}
}
}
private static HashMap<Integer, List<Pair<Integer,Integer>>> getSums(int[] arr){
HashMap<Integer, List<Pair<Integer,Integer>>> result = new HashMap<Integer, List<Pair<Integer, Integer>>>();
if (arr.length < 4){
return result;
}
for (int i = 0 ; i < arr.length-1; i++){
if (i > 0 && arr[i] == arr[i-1]){
continue;
}
for (int j = i+1; j < arr.length; j++){
if (j > i + 1 && arr[j] == arr[j-1]){
continue;
}
int sum = arr[i] + arr[j];
List<Pair<Integer,Integer>> list;
if (!result.containsKey(sum)){
list = new ArrayList<>();
result.put(sum , list);
}
else{
list = result.get(sum);
}
list.add(new Pair<>(i, j));
}
}
return result;
}
class Solution{
public<T extends Comparable<T>> ArrayList<T> merge(ArrayList<T> first, ArrayList<T> second){
if (first == null || second == null){
throw new IllegalArgumentException();
}
ArrayList<T> result = new ArrayList<T>();
int fInd = 0 , sInd = 0;
T minElement;
while(fInd < first.size() && sInd < second.size()){
if (first.get(fInd).compareTo(second.get(sInd)) < 0){
minElement = first.get(fInd);
fInd++;
}
else{
minElement = second.get(sInd);
sInd++;
}
result.add(minElement);
}
copy(first , result , fInd);
copy(second , result , sInd);
return result;
}
private<T> void copy(ArrayList<T> from, ArrayList<T> to, int fromInd){
while(fromInd < from.size()){
to.add(from.get(fromInd++));
}
}
}
public int maxDiff(int[] arr){
if (arr.length <= 1){
return Integer.MIN_VALUE;
}
int[] maxRight = new int[arr.length];
maxRight[arr.length - 1] = arr[arr.length-1];
for (int i = arr.length - 2; i >= 0; i--){
maxRight[i] = Math.max(arr[i], maxRight[i+1]);
}
int maxDiff = Integer.MIN_VALUE;
for (int i = 0 ; i < arr.length; i++){
maxDiff = Math.max(maxDiff , maxRight[i] - arr[i]);
}
return maxDiff;
}
public static int getKthElement(TreeNode root, int k){
if (k < 0 || root == null){
return Integer.MIN_VALUE;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
fillStack(stack, root);
TreeNode current;
while(!stack.isEmpty()){
current = stack.pop();
if (k == 0){
return current.val;
}
k -= 1;
fillStack(stack, current.rightChild);
}
return Integer.MIN_VALUE;
}
private static void fillStack(Stack<TreeNode> stack, TreeNode node){
while (node != null){
stack.push(node);
node = node.leftChild;
}
}
Binary search O(logn)
public static int findLocalMin(int[] arr){
return (arr.length == 0) ?
Integer.MIN_VALUE
:findLocalMin(arr, 0, arr.length-1);
}
private static int findLocalMin(int[] arr, int l , int r){
int m = l + (r-l)/2;
if (m == 0 || m == arr.length - 1){
return arr[m];
}
if (arr[m-1] > arr[m] && arr[m] < arr[m+1]){
return arr[m];
}
else if (arr[m] > arr[m+1]){
return findLocalMin(arr, m+1, r);
}
else{
return findLocalMin(arr , l , m-1);
}
}
public char charAt(String s , int position){
int index = 0;
int i = position;
while (index < s.length()){
String letters = getNextLetters(s , index);
index += letters.length();
int count = getNextNumber(s , index);
index += String.valueOf(count).length();
while (count > 0){
if (i < letters.length()){
return letters.charAt(i);
}
i -= letters.length();
count--;
}
}
return ' ';
}
private String getNextLetters(String s , int index){
StringBuilder sb = new StringBuilder();
while(index < s.length() && !isNumber(s.charAt(index))){
sb.append(s.charAt(index));
index++;
}
return sb.toString();
}
private int getNextNumber(String s, int index){
if (index >= s.length()) {
return 1;
}
int result = 0;
while(index < s.length() && isNumber(s.charAt(index))){
result = result * 10 + (s.charAt(index) - '0');
index++;
}
return result;
}
private boolean isNumber(char c){
return c >= '0' && c <= '9';
}
DP solution
public static int getCombinationsNumber(String s){
if (s.length() == 0)
return 0;
int[] dp = new int[s.length()];
dp[0] = 1;
for (int i = 1 ; i < s.length() ; i++){
int num = (s.charAt(i-1) - '0') * 10 + (s.charAt(i) - '0');
if (dp[i-1] != 0) {
dp[i] += dp[i - 1];
}
if (num <= 25) {
dp[i] += i == 1 ? 1 : dp[i - 2];
}
}
return dp[s.length()-1];
}
If you wish, you can optimize it to use O(1) memory.
- GK January 15, 2015Nice solution! My Java implementation
public static int[] sum(int[] arr){
if (arr.length == 0)
return new int[0];
int[] arr1 = new int[arr.length];
int[] arr2 = new int[arr.length];
for (int i = 1 ; i < arr.length ; i++){
arr1[i] = arr1[i-1] + arr[i-1];
}
for (int i = arr.length-2 ; i >= 0 ; i--){
arr2[i] = arr2[i+1] + arr[i+1];
}
for (int i = 0 ; i < arr.length; i++){
arr1[i] += arr2[i];
}
return arr1;
}
Suppose that : m = # of words and n = length of longest word
I know two ways how to solve this problem:
0) For each word sort it's letters and put sorted string into HashTable. O(m*n*log n)
public Collection<List<String>> GroupAnagrams(List<String> words){
final HashMap<String,List<String>> map = new HashMap<>();
words.forEach((String word ) -> {
String key = sort(word);
if (map.containsKey(key))
map.get(key).add(word);
else
map.put(key , new LinkedList<>(Arrays.asList(new String[]{word})));
});
return map.values();
}
private String sort(String str){
char[] letters = str.toCharArray();
Arrays.sort(letters);
return new String(letters);
}
1) Without HashTable.
i) Create two arrays: indexes[] and words[] where indexes[i] - position of words[i] in original array. O(m)
ii) For each string from words[] sort letters. O(m*n*logn)
iii) Sort words[]. At each swapping words[i] and words[j] have to swap indexes[i] and indexes[j] O(m*logm)
iv) Iterate through words[]. if (words[i] == words[i+1]) than words from original list standing on indexes[i] and indexes[i+1] position are anagrams. O(m)
public int divide(int dividend, int divisor) {
if (divisor == 0)
throw new IllegalArgumentException();
long p = Math.abs((long)dividend);
long q = Math.abs((long)divisor);
int result = 0;
for (int bit = Integer.SIZE - 1 ; bit >= 0 && p >= q ; bit--){
if (p >= (q << bit)){
p -= q << bit;
result |= 1 << bit;
}
}
boolean isPositive = (dividend < 0 && divisor < 0)||( dividend > 0 && divisor > 0);
if (result < 0){
//in general the result can't be negative, but in case of overflowing whe should handle it.
return isPositive ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
return isPositive ? result : -result;
}
public static void GetTypeAndMax(int[] arr){
int n = arr.length;
if (n < 2)
return;
String head = (arr[0] > arr[1]) ? "decreasing" : "increasing";
String tail = (arr[n-2] > arr[n-1]) ? "decreasing" : "increasing";
if (head.equals(tail)){
if (head.equals("increasing"))
System.out.printf("Increasing. Max elem : %d\r\n", arr[n - 1]);
else
System.out.printf("Decreasing. Max elem : %d\r\n" , arr[0]);
}
else{
if (head == "increasing"){
System.out.printf("Increasing-Decreasing. Max elem: %d\r\n" , BinSearch(arr , 0 , n-1));
}
else{
System.out.printf("Decreasing-Increasing. Max elem: %d\r\n", arr[0] > arr[n - 1] ? arr[0] : arr[n - 1]);
}
}
}
public static int BinSearch(int[] arr , int l , int r){
int m = l+ (r-l)/2;
if (arr[m-1] < arr[m] && arr[m] > arr[m+1])
return arr[m];
if (arr[l] < arr[l+1] && arr[m-1] < arr[m+1]){
return BinSearch(arr , m+1 , r);
}
else{
return BinSearch(arr, l , m);
}
}
O(n) complexity. Uses extra boolean array.
private static char[] removeDuplicates(char[] data){
if (data == null || data.length < 2)
return data;
boolean[] entries = new boolean[255];
int tail = 1;
for (int head = 1; head < data.length ; ++head){
if (data[head] == data[tail] || entries[data[head]]) {
continue;
}
data[++tail] = data[head];
entries[data[head]] = true;
}
return Arrays.copyOfRange(data , 0 , tail);
}
in-place c++ implementation
std::string transform(std::string s){
int j = 0;
for (int i = 0; i < s.length(); ++i){
if (i < s.length() - 2 && s[i] == '%' && s[i + 1] == '2' && s[i + 2] == '0'){
s[j++] = ' ';
i += 2;
}
else{
s[j++] = s[i];
}
}
return s.substr(0 , j);
}
Sure! Algorithm is quite simple.
First of all, you have to count length of s and e: |s| and |e| accordingly. Hence we have to iterate through stepping number's length from |s| and |e| (from 1 to 16 in my example).
Let's make obvious remark: leading digit can't be zero. F.e. number 012 is stepping, but it's length = 2.
Then we use simple induction:
Base : According to remark, base of induction is stepping number which contains only one digit (from 1 to 9).
Step : On the previous steps we generated stepping sequence of digits. Ok! Let's take last of them and find all possible wariants for the next one. For 0 the only possible wariant is 1 , for 9 it's 8, for others - (other-1) and (other +1). Add them to our sequence and repeat step if we haven't reached necessary length.
Here is small example:
s = 10 , e = 1000
length = 2
1 (base) -> for 1 next digit can be 0 or 2 - > hence 10 and 12 (they are stepping, length == 2 reached)
2 (base) -> for 2 next digit can be 1 or 3 -> 21 and 23
...
9 (base) -> for 9 the only variant is 8 - > 98
length = 3
1(base) -> 10 -> 101
12 -> 121 and 123
2(base) -> 21 -> 210 and 212
23 -> 232 and 234
...
Hope this explanation is clear :)
static void Dfs(long s, long e , long length , long num)
{
if (length-1 == 0)
{
if ( s <= num && num <=e)
Console.WriteLine(num);
return;
}
var lastDigit = num%10;
if (lastDigit == 0)
{
Dfs(s , e,length-1 , num*10+1);
}
else if (lastDigit == 9)
{
Dfs(s, e, length - 1, num*10 + 8);
}
else
{
Dfs(s , e,length-1 , num*10+lastDigit-1);
Dfs(s , e,length-1 , num*10+lastDigit+1);
}
}
static void Main(string[] args)
{
long s = 1;
long e = 1000000000000000;
var sLength = (int)Math.Floor(Math.Log10(s) + 1);
var eLength = (int)Math.Floor(Math.Log10(e) + 1);
for (long i = sLength; i <= eLength; ++i)
{
//no leading zero
for (long j = 1; j < 10; ++j)
{
Dfs(s , e, i , j);
}
}
}
#include <iostream>
#include <limits>
int solve(int *mice , int *holes , int M , int H , int m_from , int h_from , int max){
if (m_from == M)
return max;
int bestDistance = std::numeric_limits<int>::max();
for (int i = m_from ; i < M ; ++i){
for (int j = h_from; j < H ; ++j){
int distance = std::abs(mice[i]-holes[j]);
std::swap( mice[m_from] , mice[i] );
std::swap( holes[h_from] , holes[j]);
int result = solve(mice , holes , M , H , m_from + 1 , h_from +1 , std::max(max , distance));
if (result < bestDistance)
bestDistance = result;
std::swap( holes[j] , holes[h_from]);
std::swap(mice[i] , mice[m_from]);
}
}
return bestDistance;
}
int mice[3] = {2,0,-4};
int holes[4] = {3,1,2,-1};
int main(){
std::cout<<solve(mice , holes , 3 , 4 , 0 , 0 , 0)<<std::endl;
}
#include <iostream>
#include <string>
void permuration(std::string prefix , std::string string){
if (string.length() == 0){
std::cout<<prefix<<std::endl;
return;
}
for (int i = 0 ; i < string.length() ; ++i){
permuration(prefix + string[i] , string.substr(0 , i) + string.substr(i+1 , string.length() - i+1));
}
}
int main(){
permuration("" , "abcd");
}
#include <iostream>
#include <queue>
struct Coordinates{
int X;
int Y;
Coordinates(int x , int y) : X(x),Y(y){}
};
const int X = 10;
const int Y = 10;
char grid[X][Y] = {
{'.','.','X','.','.','.','.','.','.','.'},
{'.','.','X','.','.','.','.','.','.','.'},
{'.','.','X','.','.','.','.','.','.','.'},
{'.','.','X','.','.','.','.','.','.','.'},
{'X','X','X','.','.','.','.','.','.','.'},
{'.','.','.','.','.','.','.','X','X','X'},
{'.','.','.','.','.','.','.','X','.','.'},
{'.','.','.','.','.','.','.','X','.','.'},
{'.','.','.','.','.','.','.','X','.','.'},
{'.','.','.','.','.','.','.','X','.','.'},
};
int shifts[4][2] = {
{ -1 , 0 },
{ 1 , 0 },
{ 0, -1 },
{ 0 , 1 }
};
void draw(){
for (int x = 0; x < X; ++x){
for(int y = 0; y < Y; ++y){
std::cout<<grid[x][y];
}
std::cout<<std::endl;
}
}
bool inBounds(int x , int y){
return x >= 0 && x <X && y>=0 && y<Y;
}
void fill(int x , int y){
std::queue<Coordinates> cells;
cells.push(Coordinates(x,y));
while(!cells.empty()){
if (grid[cells.front().X][cells.front().Y] == 'X'){
cells.pop();
continue;
}
for (int i = 0 ; i < 4 ; ++i ){
Coordinates current = cells.front();
current.X += shifts[i][0];
current.Y += shifts[i][1];
if (inBounds(current.X , current.Y) && grid[current.X][current.Y] == '.')
cells.push(current);
}
grid[cells.front().X][cells.front().Y] = 'X';
cells.pop();
}
}
int main(){
draw();
fill(3,0);
draw();
}
Base class creates contract with sub classes, because of it, you can't hide base class methods.
You may try this variants:
1) override base class method. smth like :
@Override
public void test() {
throw new UnsupportedOperationException("not supported");
}
2) create interface for sub class, like
class BaseClass {
public void test(){
}
}
class SubClass extends BaseClass implements ISubClass {
public void test1() {
}
}
interface ISubClass{
void test1();
}
and make other code work with ISubClass
ISubClass example = new SubClass();
example.test1(); //ok
example.test(); //error, no such method
class Tree {
public static Boolean makeLeafAsNewRoot(Node node, Node leaf){
if (node == null)
return false;
if (node == leaf)
return true;
Node newParent;
if (makeLeafAsNewRoot(node.left, leaf)){
newParent = node.left;
node.left = null;
}
else if (makeLeafAsNewRoot(node.right, leaf)){
newParent = node.right;
node.right = null;
}
else{
return false;
}
if (newParent.left == null)
newParent.left = node;
else
newParent.right = node;
return true;
}
}
class Node {
public Node(Node left , Node right){
this.left = left;
this.right = right;
}
Node left;
Node right;
}
Suppose that all operators are binary, no brackets.
private static Map<Character, Integer> priority;
static {
priority = new HashMap<Character, Integer>();
priority.put('+',1);
priority.put('-',2);
priority.put('*',3);
priority.put('/',4);
priority.put('^',5);
}
private static Boolean isOperator(char c){
return priority.containsKey(c);
}
private static Boolean isOperand(char c){
int val = Character.getNumericValue(c);
return (0 <= val && val <= 9);
}
private static int evaluate (Character c , int b , int a) throws Exception {
switch (c) {
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
case '^':
return (int)Math.pow(a,b);
default:
throw new Exception("Unknown operator");
}
}
private static int evaluate(String s) throws Exception {
if (s.length() == 0)
return 0;
Stack<Integer> operands = new Stack<Integer>();
Stack<Character> operators = new Stack<Character>();
for (int i = 0 ; i < s.length() ; i++){
char currentChar = s.charAt(i);
if (isOperand(currentChar))
operands.push(Character.getNumericValue(currentChar));
else if (isOperator(currentChar)){
if (operators.isEmpty()) {
operators.push(currentChar);
continue;
}
if (priority.get(operators.peek()) < priority.get(currentChar)){
operators.add(currentChar);
continue;
}
char currentOperator = currentChar;
while (!operators.isEmpty() && priority.get(currentOperator) < priority.get(operators.peek())){
operands.push(evaluate(operators.pop(), operands.pop(), operands.pop()));
}
operators.push(currentChar);
}
else{
throw new Exception("Unknown lexeme");
}
}
while (!operators.isEmpty()) {
operands.push(evaluate(operators.pop(), operands.pop(), operands.pop()));
}
return operands.peek();
}
There is a hack : you may use eval function, if programming language supports such things.
For example, if you are writing in Java, you may use ScriptEngineManager.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("3+4*2");
otherwise you can build reverse polish notation, and then evaluate it.
- GK June 07, 2014This problem was already discussed many times. I've chosen the most elegant idea and implemented it
If we want to copy such linked list we should do following steps:
1) Create copy for each node and insert it next to node.
Example: was A->B->C became A->A'->B->B'->C->C'
2) Copy random links
Example: if there were connection A->C let's make connection A'->C'
3) Remove link between original node and it's copy (separate copy and original)
Totally we need to traverse three times through linked list (O(3N)) and O(1) extra memory
Here is C# implementation.
//O(3N) operations
public static Node Copy(Node start)
{
Node copy,result, original = start;
//First traverse
//For each node insert copy of node next to it
while (original != null)
{
copy = new Node
{
Val = original.Val,
Next = original.Next
};
original.Next = copy;
original = copy.Next;
}
//Second traverse
original = start;
//copy random links
//Example was A->C , copy link to nodes' copies A'->C' (-> means "Random")
while (original != null)
{
copy = original.Next;
if (original.Random != null)
copy.Random = original.Random.Next;
else
{
//this "else" block can be safely removed , because by default Random is null
//I save this code only for your understanding
copy.Random = null;
}
original = copy.Next;
}
//Third traverse
original = start;
//save the result , because now the code will destroy links between
//original nodes and copies
result = start.Next;
//destroy links between original nodes and copies
while (original!=null)
{
copy = original.Next;
original.Next = copy.Next;
if (original.Next != null)
copy.Next = original.Next.Next;
original = original.Next;
}
return result;
}
- GK March 02, 2015