Singly Linked List

Python


In [13]:
class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
    
    # in python next is a reversed word    
    def reverse(self, head):
        prev = None
        head = self
        while head:
            temp = head.next
            head.next = prev
            prev = head
            head = temp
        return prev

lk1 = ListNode(5)
lk1.next = ListNode(4)
lk1.next.next = ListNode(3)

print lk1.val
print lk1.next.val
print lk1.next.next.val
rev_lk = lk1.reverse(lk1)

print 'reversed linked list'
print rev_lk.val
print rev_lk.next.val
print rev_lk.next.next.val


5
4
3
reversed linked list
3
4
5

C++

#inlcude <iostream>
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int val, ListNode *next=NULL):val(val), next(next){};
};

ListNode *Reverseist(ListNode *head)
{
    ListNode *pre = NULL, *tmp;
    while(head)
    {
        tmp = head->next;
        head->next = pre;
        pre = head;
        head = tmp;
    }
    return pre;
}

Dual Linked List

Python


In [1]:
class DListNode:
    def __init__(self, val):
        self.val = val
        self.prev = self.next = None
        
    def reverse(self, head):
        curt = None
        while head:
            curt = head
            head = curt.next
            curt.next = curt.prev
            curt.prev = head
        return curt

TODO: add dual linked list for c++