翻转一个链表
样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
挑战
在原地一次翻转完成
代码
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
- 两根指针
public class Solution {
/*
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = null;
while (head != null) {
ListNode temp = head.next;
head.next = prev;
// 两行的赋值顺序别写反了
prev = head;
head = temp;
}
return prev;
}
}
- 用递归
public class Solution {
/*
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// 从 head.next 开始所有链表全部被翻转
// 但不包括 head.next 的前向指针
ListNode p = reverse(head.next);
head.next.next = head;
head.next = null;
// 返回链表头结点
return p;
}
}
网友评论