给定一个单链表的头结点pHead,长度为n,反转该链表后,返回新链表的表头。
数据范围: nleq1000n≤1000
要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
1,递归法首先定义Node:
java
public static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
反转方法如下:
java
public Node reverse(Node head) {
if (head == null || head.next == null)
return head;
Node temp = head.next;
Node newHead = reverse(head.next);
temp.next = head;
head.next = null;
return newHead;
}
递归实质上就是系统帮你压栈的过程,系统在压栈的时候会保留现场。
2,遍历法
public ListNode ReverseList2(ListNode head) {
//1->2->3->4
ListNode pre=null;
ListNode nextNode=null;
while (head!=null){
nextNode= head.nextNode;
head.nextNode=pre;
pre=head;
head=nextNode;
}
return pre;
}


