链表反转
public class ListReverse { static Node node1=new Node(); static { node1.data = 1; Node node2 = new Node(); node2.data = 2; Node node3 = new Node(); node3.data = 3; Node node4 = new Node(); node4.data = 4; node1.next = node2; node2.next = node3; node3.next = node4; } public Node reverse(Node node1) { Node pre = null; Node next = null; Node cur = node1; Node headNode = null; while (cur != null) { next = cur.next; if (next==null) { headNode=cur; } cur.next=pre; pre=cur; cur=next; } return headNode; } static class Node { int data; Node next; } public static void main(String[] args) { ListReverse listReverse=new ListReverse(); System.out.println("----------"+node1.data); Node node= listReverse.reverse(node1); System.out.println("----------"+node.data); }}
public class ListReverse { public Node reverse(Node node1) { Node pre = null; Node next = null; Node cur = node1; Node headNode = null; while (cur != null) { next = cur.next; if (next==null) { headNode=cur; } cur.next=pre; pre=cur; cur=next; } return headNode; }}