问题
编写一个函数,接受一条链表的首结点作为参数,(破坏性地)将链表反转并返回结果链表的首结点。
解决思路
代码
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