leetCode 92.Reverse Linked List II (反转链表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; }
 * }
 */
public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
    	/**
    	 * 本题思想是将m,n中间的链表遍历,同时计数
    	 * 3放在2前面,1-3-2-4-5
    	 * 然后4放在3前面,1-4-3-2-5
    	 * 当计数到了,结束循环
    	 */
    	ListNode first = new ListNode(0);
    	//头结点,方便统一处理
    	first.next = head;
    	
    	ListNode temp = null;
    	ListNode p = null;
    	ListNode pHead = first;//不需要反转的最后一个节点
    	ListNode pLast = null;//需要反转节点的第一个节点,将反转到最后
    	
    	int len = 0;
    	while(head != null){
    		if(++len < m){
    			pHead = head;//记录未变动的节点末尾值,如例题中的1
    			head = head.next;
    		}
    		else if(len == m){
    			//记录开始位置
    			p = pLast = head;
    			head = head.next;
    			pLast.next = null;//此句很重要,斩断之后的连接
    		}else if(len >= m && len <= n){
    			//新插入节点
    			temp = head;
    			head = head.next;//必须放这里,不然出错
    			temp.next = p;
    			p = temp;
    			pHead.next = p;
    		}else if(len > n){
    			pLast.next = head;//将已交换的链表连接上不需交换的末尾,如本例5
    			break;
    		}
    		
    	}
    	
		return first.next;
    }

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值