package nk;
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
@Override
public String toString() {
return "ListNode [val=" + val + ", next=" + next + "]";
}
}
public class Solution {
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode tmp = head;
for(int i = 2; i < 6; i++){
ListNode n = new ListNode(i);
tmp.next = n;
tmp = n;
}
print(head);
print(ReverseList(head));
}
public static ListNode ReverseList(ListNode head) {
ListNode newHead = new ListNode(0);
if(head == null) return head;
while(head != null){
ListNode tmp = newHead.next;
ListNode n = new ListNode(head.val);
n.next = tmp;
newHead.next = n;
head = head.next;
}
return newHead.next;
}
public static void print(ListNode head){
while(head != null){
System.out.print(head.val + " ");
head = head.next;
}
System.out.println("");
}
}
|