TADM2E 3.2
From Algorithm Wiki
Revision as of 05:15, 8 January 2018 by Tdtrung17693 (talk | contribs)
typedef struct Node { char *value; struct Node *next; } Node; int reverse(Node **head) { Node *curr, *prev, *next; if (!head || !(*head)) { return 0; } curr = *head; prev = NULL; next = NULL; while (curr) { next = curr->next; curr->next = prev; prev = curr; curr = next; } *head = prev; return 1; }
In Java
class ListNode { int val; ListNode next; ListNode(final int x) { val = x; next = null; } } public class LinkedList { ListNode head; public LinkedList() { head = null; } public void prepend(final int in) { final ListNode data = new ListNode(in); data.next = head; head = data; } public void appendToList(final int in) { final ListNode data = new ListNode(in); ListNode current = head; if (head == null) { head = data; return; } while (current.next != null) { current = current.next; } current.next = data; } public void printList(final ListNode head) { ListNode current = head; while (current != null) { System.out.print(current.val + " -> "); current = current.next; } System.out.println(); } public ListNode reverseList(final ListNode node) { //what if 0 node in list if (node == null) { return null; } //what if 1 node in list if (node.next == null) { return node; } //what if multiple nodes.divide into two parts . reverse second part recursively and in end point second.next to first final ListNode secondElem = node.next; node.next = null; final ListNode reverseRest = reverseList(secondElem); secondElem.next = node; return reverseRest; } public static void main(final String[] args) { final LinkedList linkedList = new LinkedList(); linkedList.appendToList(12); linkedList.appendToList(13); linkedList.appendToList(14); linkedList.appendToList(15); linkedList.printList(linkedList.head); final ListNode head = linkedList.reverseList(linkedList.head); linkedList.printList(head); } }
In Python
class Node(): def __init__(self, value): self.value = value self.next = None class LinkedList(): def __init__(self): self.head = None self.tail = None def add_node(self, value): if not self.head: self.__initialize_list(value) else: node = Node(value) self.tail.next = node self.tail = node def print_list(self): current_node = self.head print('head ->'), while current_node is not None: print(current_node.value), current_node = current_node.next print('->'), print('tail') def reverse(self): current_head = self.head head = self.head while current_head is not None: temp = current_head current_head = head.next t_next = current_head.next head.next = t_next current_head.next = temp if head.next is None: self.head = current_head break def __initialize_list(self, value): self.head = Node(value) self.tail = self.head