Leetcde25 链表反转心得

Leetcode25[Hard] 链表反转-递归

思路借鉴:递归必看,下面是 代码.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode curr = head;
    int count = 0;
    while (curr != null && count != k) { // find the k+1 node
        curr = curr.next;
        count++;
    }
    if (count == k) { // if k+1 node is found
        curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
        while (count-- > 0) { // reverse current k-group: 
        	// keep adding new node to the head of finished part.
            ListNode next = head.next; // next - next head in upgoing part
            head.next = curr; // concatenate head to finished part
            curr = head; // update the head of finished part
            head = next; // update the head of upgoing part
        }
        head = curr;
    }
    return head;
        
    }
}

三部曲模版:

1.找终止条件。 什么情况下递归终止?没得交换的时候,递归就终止了呗。因此当链表只剩一个节点或者没有节点的时候,自然递归就终止了。

2.找返回值。 我们希望向上一级递归返回什么信息?由于我们的目的是两两交换链表中相邻的节点,因此自然希望交换给上一级递归的是已经完成交换处理,即已经处理好的链表。

3.本级递归应该做什么。 由于只考虑本级递归,所以这个链表在我们眼里其实也就三个节点:head、head.next、已处理完的链表部分。而本级递归的任务也就是交换这3个节点中的前两个节点,就很easy了。

单链表反转:

//like 1->2->3->4
//思路:把当前链表的head得下一个节点next插入到dummy的下一个节点中
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0); // create a new dummy head node
        dummy.next = head;
        while(head != null && head.next !=null ){
            ListNode next = head.next; //head's next node
            head.next = next.next; //make head 1 point to 3
            next.next = dummy.next; //make 2 point to 1
            dummy.next = next; //make dummy point to 2             
        }
        return dummy.next;      
    }
}

单链表两两反转:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        while(head != null && head.next !=null ){
            ListNode next = head.next;
            head.next = next.next;
            next.next = head;
            pre.next = next;
            
            pre = head;
            head = head.next;           
        }
        return dummy.next;       
    }
}

Reference: 单链表反转总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值