数据结构(Java)---单链表的转置问题

单链表的转置需要三个元素:结点、结点的前驱、结点的后继。

public void reverse(){
        Node p=head.next;
        Node front=null;
        while(p!=null){
               Node succ = p.next;                             
                p.next = front;                                
                front = p;                                     
                p = succ;                                     
        }
         head.next = front;
    }

Node succ=p.next;是为了记录p结点的后继,并为了向后移动而建立的; p.next=front;是p的后继指向它的前驱,(若p为首结点,则p的后继为null,作为转置后的尾结点) front=p此时,p就是一个完成部分的转置单链表了,但p还要继续向后移动,所以把部分转置后的链表赋给了front结点。 p=succp移动到p的后继结点上,去完成下一轮的转置


此处使用的结点类为:

class Node{
        public Object data;
        public Node next;
        public Node(){
            this.data=null;
            this.next=null;
        }
        public Node(Object data){
            this.data=data;
            this.next=null;
        }
        public Node(Object data,Node next){
            this.data=data;
            this.next=next;
        }
    }
经验分享 程序员 微信小程序 职场和发展