您的位置:首页 > Web前端 > Node.js

反转链表

2015-10-22 16:23 573 查看
public class Solution {

         public  ListNode reverse(ListNode head, ListNode end){

           if(head==null || head.next==null || head==end || head.next==end) return head;

           ListNode sec = head.next;

           ListNode rem = reverse(sec,end);//递归,直到返回head

           sec.next =head; head.next=null;//实现反转

           return rem;

       }

        public  ListNode reverseKGroup(ListNode head, int k) {//分组反转

            ListNode curr = head; int count = 0;

            while (curr != null && count != k) {

                curr = curr.next;count++;

            }

            if (count == k) {

                ListNode temp = reverseKGroup(curr, k);

                ListNode t = reverse(head,curr);

                head.next = temp;

                return t;

            }

            return head;

        }

        

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  listnode