码迷,mamicode.com
首页 > 其他好文 > 详细

Linked List专题二(cc charpter2)

时间:2015-06-08 09:36:33      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

Reverse Nodes in k-Group 

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

分析

1.链表反转:

给一个单向链表,把它从头到尾反转过来。比如: a -> b -> c ->d 反过来就是 d -> c -> b -> a 。

这里讲解两种方法:

第一种方法就是把每个Node按照顺序存入到一个stack里面,这样,最后面一个就在最上面了。然后,把每一个再取出来,这样顺序就换过来了。

public static Node reverse(Node head) {
    Stack<Node> stack = new Stack<Node>();
    
    // put all the nodes into the stack
    while (head != null) {
        stack.add(head);
        head = head.next();
    }
    
    //reverse the linked list
    Node current = stack.pop();
    head = current;
    while (stack.empty() != true) {
        Node next = stack.pop();
        //set the pointer to null, so the last node will not point to the first node.
        next.setNext(null);
        current.setNext(next);
        current = next;
    }
    
    return head;    
}

2.用两个指针

第二种方法就是利用两个指针,分别指向前一个节点和当前节点,每次做完当前节点和下一个节点的反转后,把两个节点往下移,直到到达最后节点。

public static Node reverse(Node head) {
    Node previous = null;

    while (head != null) {
        Node nextNode = head.next();
        head.setNext(previous);
        previous = head;
        head = nextNode;
    }
        
    return previous;    
}

所以本题用两个指针的方式:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverselist(ListNode pre,ListNode next){
       
        ListNode last=pre.next;
         ListNode cur=last.next;
        while(cur!=next){
            last.next=cur.next;
            cur.next=pre.next;
            pre.next=cur;
            cur=last.next;
        }
        return last;
    }
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode newhead=new ListNode(0);
        newhead.next=head;
        ListNode pre=newhead;
        ListNode cur=head;
        int count=0;
        while(cur!=null){
            count++;
            ListNode next=cur.next;
            if(count==k){
                pre=reverselist(pre,next);
                count=0;
            }
            cur=next;
        }
        
        return newhead.next;
        
    }
}

 

Linked List专题二(cc charpter2)

标签:

原文地址:http://www.cnblogs.com/joannacode/p/4560098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!