- 迭代法:
双指针
;一个指针指向已经反转链表的尾部
,一个指针指向待反转链表的首部
,不断遍历即可
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
//已经反转链表的尾部
ListNode pre = null;
//当前要反转链表的头部
ListNode cur = head;
//待反转链表的下一节点
ListNode next = cur.next;
while(cur!=null){
next=cur.next;
cur.next=pre;
pre= cur;
cur = next;
}
return pre;
}
- 迭代
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode cur = reverseList(head.next);
head.next.next=head;
head.next=null;
return cur;
}