您的位置:首页 > 其它

反转单向和双向链表简化

2017-10-29 16:21 591 查看
 反转单向和双向链表简化:

//反转单向和双向链表
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);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息