92. Reverse Linked List II

来源:互联网 发布:婆婆定期揍儿媳 知乎 编辑:程序博客网 时间:2024/06/15 15:37

难度指数:Medium

题目要求:

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.

中文大意:一个链表,反转位置mn上的元素。注意: 1 <= m <= n <= length of list
92. Reverse Linked List II

// 使用改变值的方法不行。明确要求反转。

public ListNode reverseBetween(ListNode head, int m, int n) {        if(m == n)            return head;        int valueM = 0;        ListNode nodeM = null;        ListNode tempNode = head;        for(int i = 1 ; i <= n ; i++) {            if(i == m) {                valueM = tempNode.val;                nodeM = tempNode;                continue;            }            if(i == n) {                nodeM.val = tempNode.val;                tempNode.val = valueM;                break;            }            tempNode = tempNode.next;        }        return head;    }



正确的解决方式,注释都在代码里面,很清晰了。

要点:1.增加一个虚拟头节点  2.反转代码的逻辑。如何穿针引线起来。很棒的一道题。

public class ReverseLinkedListII92 {    public ListNode reverseBetween(ListNode head, int m, int n) {        // 首先,创建一个虚拟节点 , 这样就破解了m = 1的情况的尴尬之处。        ListNode dummyNode = new ListNode(0);        dummyNode.next = head;        head = dummyNode;        // 这样的处理方式就是服气。。。避免m = 1的尴尬。增加一个虚拟头节点对于链表问题特别好用        ListNode preNode = head;        for(int i = 1 ; i < m ; i ++) {            preNode = preNode.next;        }        // 开始进行翻转的迭代过程        ListNode constantNodeM = preNode.next;  // m位置的节点,保持不变        ListNode tempNode = preNode.next.next;        ListNode resultNode = preNode.next;   // 保存结果的node.        while(m++ < n) {            constantNodeM.next = tempNode.next;            tempNode.next = resultNode;            resultNode = tempNode;            tempNode = constantNodeM.next;        }        preNode.next = resultNode;        return head.next;    }}


原创粉丝点击