Question:
Reverse a singly linked list.
My code
/** iteration
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null)
return null;
doubleLinkedList doubleHead = new doubleLinkedList(head.val);
ListNode temp = head;
while (temp.next != null) {
doubleHead.next = new doubleLinkedList(temp.next.val);
doubleHead.next.prev = doubleHead;
doubleHead = doubleHead.next;
temp = temp.next;
}
ListNode reverseListHead = new ListNode(doubleHead.val);
ListNode reverseTemp = reverseListHead;
while (doubleHead.prev != null) {
reverseTemp.next = new ListNode(doubleHead.prev.val);
doubleHead = doubleHead.prev;
reverseTemp = reverseTemp.next;
}
return reverseListHead;
}
private class doubleLinkedList {
int val;
doubleLinkedList next;
doubleLinkedList prev;
doubleLinkedList(int x) { val = x;}
}
}
/** reversion
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null)
return null;
ListNode tail = head;
while (tail.next != null)
tail = tail.next;
reverseListNode(head);
return tail;
}
private void reverseListNode(ListNode node) {
if (node.next == null)
return;
reverseListNode(node.next);
node.next.next = node;
node.next = null;
}
public static void main(String[] argv) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = null;
Solution test = new Solution();
ListNode head = test.reverseList(node1);
while (head != null) {
System.out.println(head.val);
head = head.next;
}
}
}
My test result:
iteration:
reversion:
**
总结:
这次作业比较简单。用两种方式实现,一种是循环,一种是递归。
循环的思想比较简单,我是先另建一个双向链表,然后把单向链表存到双向链表,之后再把双向链表存到一个新的单向链表中,并返回。或者也可以用数组来实现,把链表结点存入数组,并且不断地resize,存入所有结点,在倒序构造一个新的单向链表。
递归的话,就是把这个链表当做两个部分,当前结点和当前结点之后的那段链表。先把之后的那段链表倒置,再和这个结点倒置。然后不断得递归。
作业还是比较简单的,还是要坚持每天一题。
毕业季,好冷清啊。希望今晚可以闹起来。
**
差不多的做法。
Anyway, Good luck, Richardo! -- 08/15/2016