Java 链表反转

链表数据结构如下:

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

反转链表思路:将当前链表放入stack 利用stack的特性LIFO做反转,需要注意的是stack中最后一个元素时需要讲next节点设置为null,否则后指向原始链表的第二个节点,

代码如下

public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        if(head==null){
            return null;
        }
        Stack<ListNode> stack = new Stack<>();

        while(head!=null){
            stack.push(head);//链表元素入栈
            head=head.next;
        }

        ListNode current =stack.pop(); //获得头节点
        ListNode root = current;
        while (!stack.isEmpty()){
        ListNode next = stack.pop();

            //最后一个元素时处理next为null
            if(stack.size()==0){
                next.next=null;
                current.next=next;
            }else{
                current.next=next;
                current=next;
            }

        }

        return root;
    }
}

 

posted on 2017-06-27 11:53  李乐已存在  阅读(274)  评论(0编辑  收藏  举报

AmazingCounters.com