反转单向和双向链表简化

 反转单向和双向链表简化:

//反转单向和双向链表
public class ReverseList{
     
     //节点的定义
    public static class Node{
         public int value;
         public Node next;
        
          public Node(int data)
          {
          	this.value=data;

          }
    }

    //反转单向链表
    public static Node ReverseOneList(Node head)
    {
       if(head==null|| head.next==null)
       {
       	return head;
       }
       Node pre=null;
       Node last=null;

       while(head!=null)
       {
       	last=head.next;
        head.next=pre;
       	pre=head;
       	head=last;
       }
       return pre;
    }
    
    //双向链表节点的定义
    public static class TNode{
    	 public int value;

    	 public TNode prev,next;

    	 public TNode(int data)
    	 {
    	 	this.value=data;
    	 }
    }

     //反转双向链表
    public static TNode ReverseTwoList(TNode head2)
    {
    	while(head2==null||head2.next==null)
    	{
    		return head2;
    	}
         TNode pre=null;
         TNode last=null;
    	 while(head2!=null)
    	 {
    	 	last=head2.next;
    	 	head2.next=pre;
            head2.prev=pre;
    	 	pre=head2;
    	 	head2=last;
    	 }
    	 return pre;

    }

    //打印链表
    public static void PrintList(Node head)
    {
    	while(head!=null)
    	{
    		System.out.print(head.value+"  ");
    		head=head.next;
    	}
    	System.out.println();
    }

    //打印双链表
    public static void PrintList2(TNode head)
    {
    	while(head!=null)
    	{
    		System.out.print(head.value+"  ");
    		head=head.next;
    	}
    	System.out.println();
    }
	public static void main(String []args)
	{
         Node node =new Node(1);
         node.next =new Node(2);
         node.next.next =new Node(3);
         //PrintList(node);
         Node mode=ReverseOneList(node);
         PrintList(mode);

         //双向链表的反转
         TNode tnode=new TNode(1);
          tnode.next=new TNode(2);
          tnode.next.next=new TNode(3);
          tnode.next.prev=tnode;
          tnode.next.next.prev=tnode.next;
          //PrintList2(tnode);
          TNode t=ReverseTwoList(tnode);
          PrintList2(t);
   
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值