List-Reverse List

206. Reverse Linked List

Reverse a singly linked list.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
//iterative
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        while(head != null){
            ListNode temp = head.next;
            head.next = pre;
            pre = head;
            head = temp;
        }
        return pre;
    }
}
//recursive
class Solution {
    public ListNode reverseList(ListNode head) {
       return helper(head,null);
    }
    public ListNode helper(ListNode head,ListNode res){
        if(head == null) return res;
        ListNode next = head.next;
        head.next = res;
        return helper(next,head);
    }
}
92. 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->NULLm = 2 and n = 4,

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

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
//因为头结点不确定,所以使用dummpy Node
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head == null || m > n) return head;
        ListNode dummpy = new ListNode(0);
        dummpy.next = head;
        head = dummpy;
        //首先找到m的前一个点
        for(int i = 1; i < m; i++){
            if(head == null) return null;
            head = head.next;
        }
        ListNode premNode = head;
        ListNode mNode = head.next;
        ListNode nNode = mNode,postnNode = mNode.next;
        // reverse指定范围的链表
        //走n-m-1步,因为是从m位置开始的
        for(int i = m; i < n; i++){
            if(postnNode == null) return null;
            ListNode temp = postnNode.next;
            postnNode.next = nNode;
            nNode = postnNode;
            postnNode = temp;
        }
        //首位连接逆转之后的链表
        mNode.next = postnNode;
        premNode.next = nNode;;
        return dummpy.next;
        
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值