您的位置:首页 > 其它

反转单向和双向链表

2019-02-02 16:06 253 查看
[code]package practice;

/**
* 反转单向和双向链表
* 【题目】分别实现反转单向链表和反转双向链表的函数
* 【要求】如果链表长度为N,时间复杂度要求为O(N),额外空间复杂度要求为O(1)
* @author colin.chen
*
*/
public class ReviseNode {

public static class Node{
public int value;
public Node next;

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

}

public static Node reviseNodeList(Node head){
Node pre=null;
Node next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}

public static class DoubleNode{
public int value;
public DoubleNode next;
public DoubleNode pre;

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

public static void reviseDoubleNode(DoubleNode head){
DoubleNode pre=null;
DoubleNode next=null;
while(head!=null){
pre=head.pre;
next=head.next;
head.pre=next;
head.next=pre;
head=next;
}

}

public static void main(String[] args) {
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
//		printLinkedList(head1);
//		head1 = reverseList(head1);
//		printLinkedList(head1);
//
//		DoubleNode head2 = new DoubleNode(1);
//		head2.next = new DoubleNode(2);
//		head2.next.last = head2;
//		head2.next.next = new DoubleNode(3);
//		head2.next.next.last = head2.next;
//		head2.next.next.next = new DoubleNode(4);
//		head2.next.next.next.last = head2.next.next;
//		printDoubleLinkedList(head2);
//		printDoubleLinkedList(reverseList(head2));

}

}

 

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