其他分享
首页 > 其他分享> > 206.反转链表

206.反转链表

作者:互联网

206.反转链表

给你单链表的头结点head,请你反转链表,并返回反转后的链表

输入:head = [1,2,3,4,5]

输出:[5,4,3,2,1]

1 ——> 2 输入:head = [1,2]

2 ——> 1 输出:[2,1]

提示:

  • 链表中节点的数目范围是[0,5000]
  • -5000 <= Node.val <= 5000

java: 迭代

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

解析:

以1,2,3,4,5为例

head
|
头结点 -> 1 -> 2 -> 3 -> 4 -> 5
|
curr

prev = null, curr = head


head
|
头结点 -> 1 -> 2 -> 3 -> 4 -> 5
| |
curr next

prev = null, curr = prev = null ; 这里curr 的next 等于null 把curr 的next 指向了前面的结点

head
|
头结点 <- 1 -> 2 -> 3 -> 4 -> 5
| |
prev curr

这个步骤不断重复

结果:

头结点 <- 1 <- 2 <- 3 <- 4 <- 5

标签:head,curr,val,206,反转,next,链表,ListNode,prev
来源: https://www.cnblogs.com/luketebo/p/16476341.html