您的位置:首页 > 编程语言 > Java开发

Java反转单链表(code)

2016-03-25 16:14 435 查看
class Node {

private int record;   //变量

private Node nextNode;    //指向下一个对象

public Node(int record) {
super();
this.record = record;
}
public int getRecord() {
return record;
}
public void setRecord(int record) {
this.record = record;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
}

public class ReverseSingleList {
public static Node reverse2(Node head) {
if (null == head) {
return head;
}
Node pre = head;
Node cur = head.getNextNode();
Node next;
while (null != cur) {
next = cur.getNextNode();
cur.setNextNode(pre);
pre = cur;
cur = next;
}

head.setNextNode(null);  //将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head
head = pre;

return head;
}

public static void main(String[] args) {
Node head = new Node(0);
Node tmp = null;
Node cur = null;
// 构造一个长度为10的链表,保存头节点对象head
for (int i = 1; i < 10; i++) {
tmp = new Node(i);
if (1 == i) {
head.setNextNode(tmp);
} else {
cur.setNextNode(tmp);
}
cur = tmp;
}
//打印反转前的链表
Node h = head;
while (null != h) {
System.out.print(h.getRecord() + " ");
h = h.getNextNode();
}
//调用反转方法
head = reverse2(head);
System.out.println("\n**************************");
//打印反转后的结果
while (null != head) {
System.out.print(head.getRecord() + " ");
head = head.getNextNode();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表