方法一:通过三个指针来分别指向链表的当前节点、上一节点、下一节点
分别为P1,P2,P3。
上代码:
static class Node{ int val; Node next; } public static Node reverse(Node node){ if (node==null||node.next==null){ return null; } Node current,pnext,prev; current=node.next; pnext=current.next; current.next=null; while (pnext!=null){ prev=pnext.next; pnext.next=current; current=pnext; pnext=prev; } node.next=current; return node; }
方法二:
static Node reverse2(Node node){ if (node==null||node.next==null){ return null; } Node current,pnext; current=node.next; while (current.next!=null){ pnext=current.next; current.next=pnext.next; pnext.next=node.next; node.next=pnext; } return node; }