题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
——来源于《剑指offer》
- 循环实现:用三个指针分别指向当前结点,当前结点的前一个结点,当前结点的后一个结点
package com.qianyu.jianzhioffer.reverseLinklist;
/**
* @author lijing
* @date 2019-07-28-16:16
* @discroption 反转链表
*/
public class Solution {
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode ReverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode current = head;
ListNode front = null;
ListNode behind;
while (current != null) {
behind = current.next;
current.next = front;
front = current;
current = behind;
}
return front;
}
}
- 递归实现:
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null||head.next == null) {
return head;
}
ListNode last = ReverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
}
循环不难理解,只是递归实现有些不好理解,我画了一张图,便于理解: