算法-第四版-练习1.3.30解答

问题

编写一个函数,接受一条链表的首结点作为参数,(破坏性地)将链表反转并返回结果链表的首结点。

解决思路


代码

    
    public Node<Item> reverse()
    {
        Node<Item> oldFirst = first;;
        first = null;
        while (oldFirst != null)
        {
            Node<Item> second = oldFirst.next;
            oldFirst.next = first;
            first = oldFirst;
            oldFirst = second;
        }
        return first;
    }
    

测试代码:

/**
 * Description : 
 * Author      : mn@furzoom.com
 * Date        : Oct 25, 2016 3:08:48 PM
 * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved.
 */
package com.furzoom.lab.algs.ch103;

/**
 * ClassName    : E10330 <br>
 * Function     : TODO ADD FUNCTION. <br>
 * date         : Oct 25, 2016 3:08:48 PM <br>
 * 
 * @version 
 */
public class E10330
{
    public static void main(String[] args)
    {
        LinkList<String> ll = new LinkList<String>();
        ll.append("a");
        ll.append("B");
        ll.append("c");
        ll.append("D");
        ll.append("e");
        
        ll.printList();
        ll.reverse();
        System.out.println("After reverse list:");
        ll.printList();
    }
}
    

结果:

a
B
c
D
e
After reverse list:
e
D
c
B
a


算法-第四版-1.3 背包、队列和栈-习题索引汇总

算法-第四版习题索引汇总


posted @ 2017-10-22 15:50  枫竹梦  阅读(200)  评论(0编辑  收藏  举报