1 public class ReverseDemo { 2 3 /** 4 * 单链表反转的两种方法 5 */ 6 public static void main(String[] args) { 7 Node head =new Node("a"); 8 Node node2=new Node("b"); 9 Node node3=new Node("c"); 10 head.setNext(node2); 11 node2.setNext(node3); 12 Node p=head; 13 System.out.print("链表反转前"); 14 while(p!=null){ 15 System.out.print(p.getData()); 16 p=p.getNext(); 17 } 18 Node q=reverse2(head); 19 System.out.print("链表反转后"); 20 while(q!=null){ 21 System.out.print(q.getData()); 22 q=q.getNext(); 23 } 24 25 } 26 public static Node reverse1(Node head){ 27 if(head ==null||head.getNext()==null) //递归,找到尾节点, 28 return head; 29 Node reversehead=reverse1(head.getNext()); //将尾节点设置成新头结点 30 head.getNext().setNext(head); //改变指向 31 head.setNext(null); 32 return reversehead; 33 34 } 35 public static Node reverse2(Node head){ //遍历 36 if(head==null) 37 return head; 38 39 Node pre=head; 40 Node cur=head.getNext(); 41 Node tmp; 42 while(cur!=null){ 43 tmp=cur.getNext(); //遍历结点,让该结点的后驱结点指向该结点 44 cur.setNext(pre); 45 pre=cur; 46 cur=tmp; 47 48 } 49 head.setNext(null); //最早的头结点设置指向null成为尾节点 50 return pre; //pre为新的头结点 51 52 53 } 54 55 56 }
链表反转前abc链表反转后cba
时间: 2024-10-11 11:33:18