トピック:
リストを反転リストを入力した後、出力ヘッダの新しいリスト。
回答:
解決策1:
事前入金を使用する前に、次のように最初のアイデアは、次の後の沈殿物のいずれかです。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode pre = null;
ListNode next = null;
while(head!=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
対処方法2:
再帰的には、次の通り:
public 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;
}
}