206. Reverse Linked List
12:07AM 16-09-23unknown
plain_text
a year ago
964 B
2
Indexable
Never
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { ListNode head2 = null; ListNode curr = head; while(curr != null){ head2 = insertBegin(head2,curr.val); curr = curr.next; } //head2 = removeEnd(head2); return head2; } public ListNode insertBegin(ListNode head, int x){ ListNode temp = new ListNode(x); temp.next = head; return temp; } public ListNode removeEnd(ListNode head){ ListNode curr = head; while(curr.next.next != null){ curr = curr.next; } curr.next = null; return head; } }