輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
思路一:迭代
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
Listnode cur=null,pre=head;
while(pre!=null){
Listnode t=pre.next;
pre.next=cur;
cur=pre;
pre=t;
}
return pre;
}
}
思路二:遞歸
```java
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode node = reverseList(head.next);
head.next.next = head;
head.next = null;
return node;
}
}