1 链表反转
例1:LeetCode 206。本题虽然简单但却是众多公司的面试问题。反转前后的图示如下:

在反转的过程中主要是依据指针之间的移动,如下图所示:


class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
//1 每次修改前先把head.next备份否则head修改后找不到head.next
ListNode nextTemp = head.next;
//2 修改head.next temp用来保存的是上次头节点的信息
head.next = prev;
//3 temp进行更新保存此次头节点的信息
prev = head;
//4 继续进行遍历
head = nextTemp;
}
//返回新链表的头结点
return prev;
}
}
//递归版本的实现
class Solution {
public ListNode reverseList(ListNode head) {
//递归的终止条件
if (head == null || head.next == null) return head;
//递归处理的操作是从最后一个元素开始的
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}
与此类似的有题目:LeetCode:92
0