链表之单、双链表反序

来源:互联网 发布:英克灵智医药软件 编辑:程序博客网 时间:2024/06/15 11:41

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

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;       }       }

给定一个双链表反序

public class DoubleNode {            public int value;            public  DoubleNode last;            public   DoubleNode next;            public DoubleNode(int data){                this.value=data;            }            public DoubleNode(){}            //反序函数            public DoubleNode reverseList(DoubleNode head){            DoubleNode pre=null;            DoubleNode next=null;                while(head!=null){                next=head.next;                head.next=pre;                head.last=next;                pre=head;                head=next;                }                return next;            }}



0 0