java算法题-反转链表
直接上代码,因为是在线编辑器,很多package都省略了,主要是看关键代码;通过递归方式反转链表
```java
public class HelloWorld{
public static void main(String []args){
ListNode node5 = new ListNode(5,null);
ListNode node4 = new ListNode(4,node5);
ListNode node3 = new ListNode(3,node4);
ListNode node2 = new ListNode(2,node3);
ListNode node1 = new ListNode(1,node2);
printListNode(node1);
ListNode res = reverseList(node1);
System.out.println();
System.out.print("reverser result is:");
printListNode(res);
}
private static void printListNode(ListNode node){
while(node!=null){
System.out.print(node.val +(node.next!=null ? "->":""));
node = node.next;
}
}
public static class ListNode{
public int val;
public ListNode next;
public ListNode(int val,ListNode next){
this.val = val;
this.next = next;
}
}
private static ListNode reverseList(ListNode head){
if(head ==null || head.next==null) return head;
ListNode listRes = reverseList(head.next);
head.next.next = head;
head.next = null;
return listRes;
}
}
补充:迭代法
```java
public static ListNode diedai(ListNode head){
ListNode preNode=null,next,curNode;
curNode = head;
while(curNode!=null){
next = curNode.next;
curNode.next = preNode;
preNode = curNode;
curNode = next;
}
return preNode;
}
```java
### 运行结果:
1->2->3->4->5
reverser result is:5->4->3->2->1
没有什么优雅的代码比空代码的执行效率更高