【LeetCode】【算法】206. 反转链表
LeetCoe 206. 反转链表
题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
思路
思路:三个指针,一个指针指向当前指针的前一个节点,不断遍历以实现反转
代码
/**
* 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) {
ListNode prev = null;
ListNode cur = head;
while (cur != null){
ListNode tmp = cur.next;
cur.next = prev;
prev = cur;
cur = tmp;
}
return prev;
}
}