Java:
public class TestNode {
private static Node initNode(){
Node node5 = new Node(5,null);
Node node4 = new Node(4,node5);
Node node3 = new Node(3,node4);
Node node2 = new Node(2,node3);
Node node1 = new Node(1,node2);
return node1;
}
public static void main(String[] args) {
Node node = initNode();
node.print();
System.out.println("------");
Node reverseNode = reversalNode(node);
reverseNode.print();
}
private static Node reversalNode(Node node) {
if (null == node || null == node.getNext()) {
return node;
}
Node pre = null;
Node cur = node;
while (null != cur) {
Node nextNode = cur.next;
cur.setNext(pre);
pre = cur;
cur = nextNode;
}
return pre;
}
static class Node {
int value;
Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
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;
}
public void print(){
Node node = this;
while (null != node) {
System.out.println("node " + node.value);
node = node.getNext();
}
}
}
}
python:
class Node:
def __init__(self,value,nextNode):
self.value = value
self.nextNode = nextNode
def getValue(self):
return self.value
def getNextNode(self):
return self.nextNode
def main():
node5 = Node(5,None)
node4 = Node(4,node5)
node3 = Node(3,node4)
node2 = Node(2,node3)
node1 = Node(1,node2)
node = node1
while (node):
print "node",node.value
node = node.nextNode
print "------"
cur = node1
per = None
while(cur):
next = cur.nextNode
cur.nextNode = per
per = cur
cur = next
while (per):
print "node",per.value
per = per.nextNode
if __name__=="__main__":
main()