- n1, n2 are apart (1+ nodes).
- n1, n2 are adjacent i.e. n1->n2 or n2->n1.
- n1, n2 could be head or tail.
- n1, n2 may not exist in linked list.
//case 1: pn1-n1-an1 pn2-n2-an2 //case 2: pn1-n1-n2-x //case 3: pn2-n2-n1-x In each cash, n1 or n2 could be head or tail.For singly linked list:
singly-linkedlist: node head, tail swap(n1, n2): if head == null || n1 == null || n2 == null: throw if n1 == n2: return pn1 = previous(n1) pn2 = previous(n2) if n1.next == n2: // n1->n2 if pn1 != null: pn1.next = n2 n1.next = n2.next n2.next = n1 else if n2.next == n1: // n2->n1 if pn2 != null: pn2.next = n1 n2.next = n1.next n1.next = n2 else: an1 = n1.next an2 = n2.next if pn1 != null: pn1.next = n2 n2.next = an1 if pn2 != null: pn2.next = n1 n1.next = an2 // head if n1 == head: n2 = head else if n2 == head: n1 = head // tail if n1 == tail: n2 = tail else if n2 == tail: n1 = tail node previous(x): if head == null || x == null: throw if x == head: return null prev = null n = head while n != null: if n == x: break prev = n n = n.next if n == null: throw "x not present" return prevFor doubly linked list:
doubly-linkedlist: node head, tail swap(n1, n2): if head == null || n1 == null || n2 == null: throw if n1 == n2: return pn1 = previous(n1) pn2 = previous(n2) if n1.next == n2: // n1->n2 x = n2.next if pn1 != null: pn1.next = n2 n2.prev = pn1 n1.next = x if x != null: x.prev = n1 n2.next = n1 n1.prev = n2 else if n2.next == n1: // n2->n1 x = n1.next if pn2 != null: pn2.next = n1 n1.prev = pn2 n2.next = x if x != null: x.prev = n2 n1.next = n2 n2.prev = n1 else: an1 = n1.next an2 = n2.next if pn1 != null: pn1.next = n2 n2.prev = pn1 n2.next = an1 if an1 != null: an1.prev = n2 if pn2 != null: pn2.next = n1 n1.prev = pn2 n1.next = an2 if an2 != null: an2.prev = n1 // head if n1 == head: n2 = head else if n2 == head: n1 = head // tail if n1 == tail: n2 = tail else if n2 == tail: n1 = tail[Hat tip to PC]
No comments:
Post a Comment