递归写法:
/*
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 nextNode = head.next; //记录head的next节点
ListNode newHead = reverseList(nextNode); //递归翻转
nextNode.next = head;
head.next = null;
return newHead;
}
}
非递归写法:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution
{
public ListNode ReverseList(ListNode head)
{
ListNode pre = null;
ListNode next = null;
while(head!=null)
{
next = head.next; //记录head的next节点
head.next = pre; //翻转
pre = head;
head = next; //pre、head依次向后移动一个节点,继续翻转
}
return pre;
}
}