Data Structure

Linked list

Learn data structure by example of singly and doubly linked list algorithm

4/25/2021
0 views
singly-linkedlist-algorithm.cC
/* Singly Linked list */

/* Insert node at beginning */
addFirst(String newData):
  create a new node v containing newData
  v.setNext(head)
  head = v
  size = size + 1


/* Insert node at end */
addLast(String newData):
  create a new node v containing newData
  v.setNext(null)

  /* list is empty */
  if (head == null) {  
      head = v

  /* list is not empty */
  } else {
      tail.setNext(v)
  }
  tail = v
  size = size + 1

  
/* Delete node */
remove()
  if (head = = null) then
    Indicate an error: the list is empty
  tmp = head
  head = head.getNext()
  tmp.setNext(null)
  size = size - 1


/* Traverse linked list */
traverseList()
  curNode = head
  while (curNode != null)  {
     /* print out the contents of the current node */
     curNode = curNode.getNext()
  }
doubly-linkedlist-algorithm.cC
/* Doubly Linked list */


/* Insert node at beginning */
addFirst(v):

    /* the current first node */
    w = header.getNext() 
    v.setNext(w)
    w.setPrev(v)
    header.setNext(v)
    v.setPrev(header)
    size++


/* Insert node at end */
 addAfter(v, z): 
    w = v.getNext()
    v.setNext(z)
    z.setPrev(v)
    z.setNext(w)
    w.setPrev(z)
    size++


/* Delete node */
remove():

    /* the current last node */
    v = trailer.getPrev()
    if (v = = header) then
        Indicate an error: the list is empty
    prev = v.getPrev()
    prev.setNext(trailer)
    trailer.setPrev(prev)
    v.setPrev(null)
    v.setNext(null)
    size--
data structuredata structure algorithmlinked list algorithmsingly linked listdoubly linked list

Loading comments...

Related Examples