题目描述
Reverse a singly linked list.
解题思路
用一个辅助的List,然后逆序
代码
package com.larry.easy;
import java.util.ArrayList;
import java.util.List;
import com.larry.util.ListNode;
public class ReverseLinkedList {
public ListNode reverseList(ListNode head){
if(head == null) return null;
List<ListNode> list = new ArrayList<ListNode>();
while(head != null){
list.add(head);
head = head.next;
}
for(int i = list.size()-1; i > 0; i--)
list.get(i).next = list.get(i-1);
list.get(0).next = null;
return list.get(list.size()-1);
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
ListNode head = node5;
new ReverseLinkedList().reverseList(head).print();
}
}<span style="color:#ff0000;">
</span>