題目描述
輸入一個鏈表,反轉(zhuǎn)鏈表后,輸出鏈表的所有元素。
迭代法
/*
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){
return null;
}
ListNode newHead = null;
ListNode tmp = null;
while(head!=null){
tmp = newHead;
newHead = head;
head = head.next;
newHead.next = tmp;
}
return newHead;
}
}
遞歸法:
/*
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 p = ReverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}