链表篇-反转链表

2019-05-23  本文已影响0人  v_vOctopus

题目

输入一个链表,反转链表。

1、思路

利用三个指针,分别指向当前节点、当前节点前一个节点、当前节点后一个节点,并将他们调换顺序。

2、代码

public class 反转链表 {
    public ListNode ReverseList(ListNode head) {
        ListNode pre = null, next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读