Created
May 14, 2017 11:55
-
-
Save thanlau/0b6d172c94d14c5fbbe26f070fa0d463 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//define linkedNode | |
class LinkedNode{ | |
int val; | |
LinkedNode next; | |
public LinkedNode(int val){ | |
this.val = val; | |
this.next = next; | |
} | |
} | |
class Solution{ | |
public static void main(String[] args) throws java.lang.Exception | |
{ | |
LinkedNode head = new LinkedNode(1); | |
LinkedNode node1 = new LinkedNode(2); | |
LinkedNode node2 = new LinkedNode(4); | |
LinkedNode node3 = new LinkedNode(5); | |
LinkedNode node4 = new LinkedNode(7); | |
head.next = node1; | |
node1.next = node2; | |
node2.next = node3; | |
node3.next = node4; | |
LinkedNode headtmp = head; | |
System.out.print("Original list: "); | |
while(head !=null){ | |
System.out.print(head.val); | |
System.out.print("->"); | |
head = head.next; | |
} | |
System.out.print("null"); | |
System.out.println("Reversed list: "); | |
head = reverse(headtmp); | |
while(head !=null){ | |
System.out.print(head.val); | |
System.out.print("->"); | |
head = head.next; | |
} | |
System.out.print("null"); | |
} | |
public static LinkedNode reverse(LinkedNode head) { | |
LinkedNode prev = null; | |
while(head !=null){ | |
LinkedNode temp = head.next; | |
head.next = prev; | |
prev = head; | |
head = temp; | |
} | |
return prev; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment