https://leetcode.com/problems/reverse-linked-list/
解题思路:
这里使用迭代实现的链表反转,链表反转时需要做两件事,一是将当前节点指向前一个节点,二是移动节点继续迭代。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode prev = head;
ListNode curr = head.next;
head.next = null;
while (prev != null && curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}