链表之单、双链表反序

83 阅读1分钟

给定一个单链表,然后对它反序。

ListNode类

 

public class ListNode {
       int val;
       ListNode next;
       ListNode(int x){
    	   val=x;
    	   next=null;
       }
       ListNode(){}
       ListNode(int x,ListNode node){
    	   val=x;
    	   next=node;
       }
       public void setVal(int val){
    	   this.val=val;
       }
       public int getVal(){
    	   return val;
       }
       public void setListNode(ListNode next){
    	   this.next=next;
       }
       public ListNode getListNode(){
    	   return next;
       }
       //单链表反序
       public ListNode reverse(ListNode head){
    	      ListNode pre=null;
    	      ListNode next=null;
    	      while(head!=null){
    	    	  next=head.next;
    	    	  head.next=pre;
    	    	  pre=head;
    	    	  head=next;
    	      }
    	      return pre;
       }
       
}


给定一个双链表反序