Reverse Linked List
Reverse a singly linked list.

click to show more hints.

Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?

  1. 非递归

public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode p=head,q=head.next,next=null;
        head.next=null;
        while(q!=null){
            next=q.next;
            q.next=p;
            p=q;
            q=next;
        }
        return p;
    }
}

2.递归

public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode tmp=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return tmp;
    }
}

Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

代码

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null||head.next==null) return head;
        ListNode dummy=new ListNode(0);
        dummy.next=head;
        ListNode pre=dummy,p=head;
        int count=1;
        while(count<m){
            pre=p;
            p=p.next;
            count++;
        }
        ListNode pm=p;
        ListNode q=p.next,next=null;
        
        while(count<n){
            next=q.next;
            q.next=p;
            p=q;
            q=next;
            count++;
        }
        ListNode pn=p;
        pre.next=pn;
        pm.next=q;
        return dummy.next;
    }
}

tiffanytown
6 声望2 粉丝

keep learning