206. 反转链表 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/reverse-linked-list/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode cur = null, pre = head;
while (pre != null) {
ListNode swap = pre.next;
pre.next = cur;
cur = pre;
pre = swap;
}
return cur;
}
}
思路还是比较简单的,三个节点,一个在前,一个在后,一个用来交换,while循环过一遍。