题目描述:
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
思路分析:
-
递归法
该题可以用递归处理。一直递归到最后一个结点,然后翻转最后一个结点,然后翻转倒数第二个结点…返回之前的尾结点,即翻转后的首结点。
参考代码:
public static ListNode reverseList(ListNode head) {
if(head == null || head.next == null)return head;
ListNode root = reverseList(head.next);
head.next.next = head;
head.next = null;
return root;
}
-
迭代法:
设置3个指针pre,curr,next,分别表示前一个结点,当前节点,后一个结点,然后从前到后进行翻转。
参考代码:
public static ListNode reverseList(ListNode head) {
if(head == null || head.next == null)return head;
ListNode pre = null;
ListNode curr = head;
ListNode next = head.next;
while(next != null){
curr.next = pre;
pre = curr;
curr = next;
next = next.next;
}
curr.next = pre;
return curr;
}
(完)