单链表反转问题

基本问题

如何将单链表反转?

单链表结构定义


/**
 * Description: Definition for singly-linked list.
 * 
 * @date: 2016-9-17 下午12:11:13
 */
public class ListNode {
    public int      val;
    public ListNode next;

    public ListNode(int x) {
        val = x;
    }
}

算法实现

/**
 *
 * Description: 单链表反转.
 *
 * @param  head
 * @return  ListNode
 */
public   static  ListNode reverseList(ListNode head)
{
    if  (head ==  null ) {
        return  head;
    }
    ListNode prev =  null ;
    ListNode current = head;
    ListNode next =  null ;
    while  (current !=  null ) {
        next = current. next ;
        current. next  = prev;
        prev = current;
        current = next;
    }
    head = prev;
    return  head;
}

进阶问题

如何 将单链表在指定区间内进行反转?

问题分析

这个问题是上面问题的一个变形,难度也加大了不少,主要的难点之处就在于对边界条件的检查。
实现思路,主要就是按照给定的区间得到需要整体反转的一个子链表然后进行反转,最后就是把链表按正确的顺序拼接在一起。

算法实现


/**
 *
 * Description: 单链表反转,反转制定区间内的节点.
 *
 * @param  head
 * @param  m
 * @param  n
 * @return  ListNode
 */
public   static  ListNode reverseBetween(ListNode head,  int  m,  int  n)
{
    // 合法性检测
    if  (head ==  null  || m >= n || m < 1 || n < 1) {
        return  head;
    }
    /**
    * 将链表按[m,n]区间分成三段.
    *
    * first,second,third分别为每一段的头节点(注意,m=1也就是first与second相等的情况的处理)
    * first --> firstTail
    * second
    * third
    */
    ListNode first = head;
    ListNode firstTail = first;
    ListNode second = first;
    ListNode third = first;
    ListNode current = first;
    int  i = 0;
    while  (current !=  null ) {
        i++;
        if  (i == m - 1) {
            firstTail = current;
        }
        if  (i == m) {
            second = current;
        }
        if  (i == n) {
            third = current. next ;
            break ;
        }
        current = current. next ;
    }
    // 进行中间second段的reverse
    current = second;
    ListNode prev = third;
    ListNode next =  null ;
    while  (current != third) {
        next = current. next ;
        current. next  = prev;
        prev = current;
        current = next;
    }
    if  (m == 1) {
        first = prev;
    }  else  {
        firstTail. next  = prev;
    }
    return  first;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值