LeetCode:206. 反转链表

力扣链接

算法思想:由于单链表是单向的,想要对当前元素进行操作,需找到前一个元素。本题利用双指针,初始pre指针指向NULL,cur指针指向head.再对局部翻转之前,先把下一个结点存到temp指针中。当进行完如下代码逻辑后,此时cur指针指向NULL,pre指针指向头结点

代码

/**
 * 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 pre = null, cur = head;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;  
     
    }
}

你可能感兴趣的:(leetcode,链表,算法)