面试之路(28)-反转链表(reverse ListNode)

反转链表:

java类

public class ListNode{
    int key;
    ListNode next;
}

思路分析:

  • 需要三个指针,current,prev和next。
  • current.next = prev之前需要next = current.next(判断next是否为空),同时一直往后遍历
  • while(node != null)

代码:

public ListNode reverseList(ListNode head){
        ListNode prev = null;
        ListNode node = null;
        ListNode current = head;
        while(current != null){
            ListNode next = current.next;
            if(next == null){
                node = current;
            }
            current.next = prev;
            prev = current;
            current = next;
        }
        return node;
    }
    原文作者:fengsehng
    原文地址: https://blog.csdn.net/lpjishu/article/details/51356363
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞