反转链表为经典的面试算法题,
题目描述
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
数据范围: 0≤n≤1000
要求:空间复杂度 O(1) ,时间复杂度 O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
1,双指针递归解法(思路简单):
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null) return null;
//第一个指针指向NULl,第二个指向head,即A->B-NULL(如NULL->A->B->NULL变为NUll<-A<-B<-NULL)
return method(null, head);
}
public ListNode method(ListNode pre1, ListNode head) {
ListNode temp;
ListNode pre = pre1;
ListNode current = head;
if (current == null) {
//当前指针current指向null时,返回pre指针指向的链表,为最终结果
return pre;
}
//临时变量,保存cur指针准备向后移动的Node,因current.next方向需要反转,current.next值会变化
temp = current.next;
//反转,cur的next指向前一个node(如NULL->A->B->NULL变为NUll<-A<-B<-NULL)
current.next = pre;
//pre指针向后移动
pre = current;
//cur指针向后移动
current = temp;
//递归
return method(pre, current);
}
}