
方法一:迭代法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode reverseList(ListNode head) { ListNode node =head; ListNode newHead=null; while(node!=null){ ListNode tmp=node.next; node.next=newHead; newHead=node; node=tmp; } return newHead; }}
方法二:递归法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode reverseList(ListNode head) { if(head==null||head.next==null) return head; else{ ListNode newHead=reverseList(head.next); head.next.next=head; head.next=null; return newHead; } }}