java链表反转
2016-12-08 17:10
375 查看
这里只实现遍历反转,还有一种递归反转这里未实现
/**
* 链表反转
* @author DELL
*
*/
public class LinkReverse {
/**
* @param args
*/
public static void main(String[] args) {
Node n0 = new Node(0);
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
n0.next=n1;
n1.next=n2;
n2.next=n3;
System.out.println(n0.getValue()+"-----"+n1.getValue()+"-----"+n2.getValue()+"-----"+n3.getValue());
Node result = reverse(n0);
System.out.println(result.getValue()+"-----"+result.getNext().getValue()+"-----"+result.getNext().getNext().getValue()+"-----"+result.getNext().getNext().getNext().getValue());
}
/**
* 遍历反转
* @param head
* @return
*/
public static Node reverse(Node head){
if(head==null||head.next==null){
return null;
}
Node pre = head;//前一节点
Node cur = head.getNext();//当前节点
head.setNext(null);
Node next = null;//下一节点
while(cur!=null){
next = cur.getNext();
cur.setNext(pre);
pre = cur;
cur = next;
}
return pre;
}
}
class Node{
int value;
Node next;
public Node(int value) {
super();
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
/**
* 链表反转
* @author DELL
*
*/
public class LinkReverse {
/**
* @param args
*/
public static void main(String[] args) {
Node n0 = new Node(0);
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
n0.next=n1;
n1.next=n2;
n2.next=n3;
System.out.println(n0.getValue()+"-----"+n1.getValue()+"-----"+n2.getValue()+"-----"+n3.getValue());
Node result = reverse(n0);
System.out.println(result.getValue()+"-----"+result.getNext().getValue()+"-----"+result.getNext().getNext().getValue()+"-----"+result.getNext().getNext().getNext().getValue());
}
/**
* 遍历反转
* @param head
* @return
*/
public static Node reverse(Node head){
if(head==null||head.next==null){
return null;
}
Node pre = head;//前一节点
Node cur = head.getNext();//当前节点
head.setNext(null);
Node next = null;//下一节点
while(cur!=null){
next = cur.getNext();
cur.setNext(pre);
pre = cur;
cur = next;
}
return pre;
}
}
class Node{
int value;
Node next;
public Node(int value) {
super();
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
相关文章推荐
- Java单双链表的创建、反转与递归反转
- 反转链表的Java实现
- Java实现单链表反转
- java之链表反转
- Java实现反转单链表
- 单链表的反转java实现
- 【LeetCode-面试算法经典-Java实现】【092-Reverse Linked List II(反转单链表II)】
- java-实现链表反转-递归和非递归实现
- Java中单链表的实现和单链表的反转(倒置)
- java实现链表反转
- Java链表反转(复习.复习)
- 【Java数据结构】Java数据结构之链表反转
- 反转链表(不改变指针)JAVA版
- Java单链表反转与部分反转
- 单链表反转(Singly Linked Lists in Java)
- Java单双链表的创建、反转与递归反转
- 不依赖堆栈的链表反转——java实现
- 反转链表_Java实现
- 剑指Offer-题16 反转链表(Java)
- 剑指Offer面试题16(Java版):反转链表