java 实现反转链表

来源:互联网 发布:访客网络需要开启吗 编辑:程序博客网 时间:2024/05/16 06:02

         上篇是半懂不懂的就写下来了,运行结果还是对的,今天是真想明白了,大家跟着我的思路走:我不得不吐槽csdn的编译器了,华哥链表都没有ppt上的容易,那就文字描述吧:

         实现反转主要是让其next指向pre即前一个节点,那么只需循环:

 while(p!=null){            pNext=p.next;            p.next=pre;            pre=p;            p=pNext;        }

只要不断裂原列表后面的next指针,而新列表的next执行很可以构建就可完成这个人任务了,下面是所有代码:

package fanzhuanLinkedList;/** * Created by Administrator on 2015/11/4 0004. */public class Test2 {    public static void main(String[] args) {        Node head=new Node(0);        Node t;        Node cur=head;        for(int i=1;i<10;i++){            t=new Node(i);            cur.next=t;            cur=t;        }        show(head);        Node curNew=fanzhuan(head);        show(curNew);    }    private static Node fanzhuan(Node cur) {        if(cur==null)            return null;        Node pre=null;        Node p=cur;        Node pNext=null;        while(p!=null){            pNext=p.next;            p.next=pre;            pre=p;            p=pNext;        }        return pre;    }    private static void show(Node cur) {        while(cur!=null){            System.out.print(cur.value+" ");            cur=cur.next;        }        System.out.println();    }    static class Node{        int value;        Node next;        public Node(int value) {            this.value = value;            next=null;        }    }}






0 0
原创粉丝点击