Concatenate two circular linked lists

Write a program to concatenate two circular linked lists into a single circular list.

Questions by vivek180984

Showing Answers 1 - 3 of 3 Answers

Hi
It is very simple.
Get the Node values from first Circular list and stored in one temp. array.
You can keep track of repeated values by checking and comparing each value and then put into array.

Now you can add all this array values into second link list.

  Was this answer useful?  Yes

j_l_larson

  • Oct 19th, 2009
 

class node {
public:
  node(int n) : m_n(n) { m_pNext = this; }
  ~node() {}
  void SetNext( node* p ) { m_pNext = p; }
  node* GetNext() const { return m_pNext; }
  int GetData() const { return m_n; }
  static void deleteNode(node* p) { delete p; }
private:
  int m_n;
  node* m_pNext;
};

typedef void (*visitFnc)(node*);

class CyclicList {
public:
  CyclicList() { Null(); }
  ~CyclicList() {
    Visit(node::deleteNode);
  }
  void Null() { m_pTail = m_pHead = NULL; }
  void Append(int n) {
    node* p = new node(n);
    if ( ! m_pHead ) {
      m_pHead = m_pTail = p;
      return;
    }
    m_pTail->SetNext(p);
    p->SetNext( m_pHead );
    m_pTail = p;
  }
  void Visit( visitFnc f ) {
    node* p = m_pHead;
    while (p) {
      node* pNext = p->GetNext();
      f(p);
      if ( p == m_pTail )
        break;
      p = pNext;
    }
  }
  void Join( CyclicList& cl ) {
    if ( cl.m_pHead == NULL )
      return;
    if ( m_pHead == NULL ) {
      m_pHead = cl.m_pHead;
      m_pTail = cl.m_pTail;
      cl.Null();
      return;
    }
    m_pTail->SetNext(cl.m_pHead);
    cl.m_pTail->SetNext(m_pHead);
    m_pTail = cl.m_pTail;
    cl.Null();
  }
private:
  node* m_pHead;
  node* m_pTail;
};

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions