package 剑指offer;
/**
* @author guoliang
*/
public class ReverseSingleList {
public static void main(String [] args){
Node head = new Node(0);
Node temp = null;
Node cur = null;
for(int i = 1;i < 10;i++){
temp = new Node(i);
if(i != 1){
cur.setNextNode(temp);
}else{
head.setNextNode(temp);
}
cur = temp;
}
Node before = head;
while(before != null){
System.out.print(before.getRecord()+" ");
before = before.getNextNode();
}
head = reverse(head);
System.out.println("\n**************************");
//打印反转后的结果
while (null != head) {
System.out.print(head.getRecord() + " ");
head = head.getNextNode();
}
}
public static Node reverse(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;
}
//将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head
head.setNextNode(null);
head = pre;
return head;
}
//变量
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;
}
}
/**
* @author guoliang
*/
public class ReverseSingleList {
public static void main(String [] args){
Node head = new Node(0);
Node temp = null;
Node cur = null;
for(int i = 1;i < 10;i++){
temp = new Node(i);
if(i != 1){
cur.setNextNode(temp);
}else{
head.setNextNode(temp);
}
cur = temp;
}
Node before = head;
while(before != null){
System.out.print(before.getRecord()+" ");
before = before.getNextNode();
}
head = reverse(head);
System.out.println("\n**************************");
//打印反转后的结果
while (null != head) {
System.out.print(head.getRecord() + " ");
head = head.getNextNode();
}
}
public static Node reverse(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;
}
//将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head
head.setNextNode(null);
head = pre;
return head;
}
}
//构建一个链表
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;
}
}