反转链表
以下是两种解法
递归法解决反转链表,先递归调用找到尾节点并记录,记录节点时候此时的head指针指向的是尾节点的上一个节点,我们利用head.next.next = head,让尾节点的指针指向head,然后进行递归循环。
java
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(head);
}
private ListNode reverse(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode R = reverse(head.next);//R拿到的是尾节点,此时head为R尾节点的上一个节点
head.next.next = head;
head.next = null;
return R;
}
}第二种迭代双指针,创建一个pre指针指向空值,用一个cur指针代替head指针进行移动,只要cur不为空,我们用一个指针nex记录cur的下一个节点,然后让cur.next指向pre,然后pre指向cur,此时箭头与顺序相反,这是我们想达到的目的,然后将cur指向到nex指向的节点。最后pre指针刚好是尾节点。
java
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode nex = cur.next;
cur.next = pre;
pre = cur;
cur = nex;
}
return pre;
}
}