Java实现反转链表

    技术2022-07-11  102

     

    package suanfa; /** *author:bingbing *日期:2020年7月1日 *时间:下午11:14:02 */ public class demo09 { public static class Node{ int v=0; Node next; Node(int v){ this.v=v; } public String show() { return this.v + "->" + (this.next == null ? "NULL" : this.next.show()); } } public static void main(String[] args) { System.out.println("5->4->3->2->1->null"); Node head=new Node(5); Node fourth=new Node(4); Node third=new Node(3); Node second=new Node(2); Node first=new Node(1); head.next=fourth; fourth.next=third; third.next=second; second.next=first; System.out.println("反转链表"); System.out.println(reverseList(head).show()); } public static Node reverseList(Node head) { //从第一个节点开始遍历,遍历到尾节点为空时,停止替换动作。 Node pre=null; while(head!=null) { Node current=head; // current 5 head 5 head=head.next; // current 5 head 4 current.next=pre; // current 5 head 4 pre=current; // current 5 head 4 pre=5 第一轮结果为: 5 第二轮结果为 :4->5 System.out.println("current:"+current.v); } return pre; } }

     

    Processed: 0.014, SQL: 9