最后我的解决方案还是栈:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
//利用栈
if(head == null)
{
return null;
}
Stack stack = new Stack();
ListNode p = head;
while(p.next != null)
{
stack.add(p.val);
p = p.next;
}
stack.add(p.val);//最后一个节点的值
ListNode head2 = new ListNode((Integer)(stack.pop()));
ListNode p2 = head2;
while(!stack.isEmpty())
{
p2.next = new ListNode((Integer)(stack.pop()));
p2 = p2.next;
}
return head2;
}
}
但是考察的肯定不是希望怎么来,应该用指针,动态规划去解决。
public static void main(String[] args) {
ListNode listNode = ListNodeUtils.buildListNode(1, 2, 3);
ReverseLink reverseLink = new ReverseLink();
ListNode listNode1 = reverseLink.reverseList(listNode);
AssertUtils.assertListNode(listNode1, 3, 2, 1);
ListNode listNode2 = ListNodeUtils.buildListNode(1, 2, 3, 4, 5);
ListNode listNode3 = reverseLink.reverseList2(listNode2);
AssertUtils.assertListNode(listNode3, 5, 4, 3, 2, 1);
}
/**
* 用两个指针,一个指向前一个,一个指向后一个
* @param head
* @return
*/
public ListNode reverseList(ListNode head) {
// 迭代
ListNode p1 = null;
ListNode p2 = head;
while (p2 != null) {
ListNode nextNode = p2.next;
ListNode curNode = p2;
p2.next = p1;
p1 = curNode;
p2 = nextNode;
}
return p1;
}
/**
* 递归
* 思路同理
* @param head
* @return
*/
public ListNode reverseList2(ListNode head) {
ListNode p1 = null;
ListNode p2 = head;
return recursion(p1 ,p2);
}
private ListNode recursion(ListNode p1, ListNode p2) {
if (p2 == null) {
return p1;
}
ListNode next = p2.next;
p2.next = p1;
p1 = p2;
p2 = next;
return recursion(p1, p2);
}