单链表反转的实现
作为一道经典的面试题,链表反转说起来容易,真正要写出代码还是有一点难度(对于新手),在试错了好几次后,总算是磕磕绊绊的写出来了,下面将代码的思路记录下来。
链表代码如下:
// Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
迭代法:
遍历旧链表的节点,并依次添加到新链表的头部。
class Solution {
public ListNode reverseList(ListNode head) {
// 创建新的链表用来储存旧链表节点
ListNode newNode = null;
while (head != null) {
// 创建一个临时节点记录当前节点的下一个节点
ListNode tempNode = head.next;
// 第一次:第一个节点指向null,第二次:第二个节点指向第一个节点,以此类推
head.next = newNode ;
// 将head赋值给newNode,此时newNode就是新链表的头结点
newNode = head;
// 将临时节点(下一个节点)赋值给head,继续进行遍历
head = tempNode;
}
return newNode;
}
}
递归法:
class Solution{
public ListNode reverseList(ListNode head){
// 递归终止条件
if(head == null || head.next == null){
return head;
}
// 递归
ListNode newNode = reverseList(head.next);
// 让后一个节点指向当前节点
head.next.next = head;
// 当前节点指向null,避免形成环
head.next = null;
return newNode;
}
}