翻转链表(非递归)

1. 问题描述:

给出一个链表,翻转链表,返回翻转后链表的头结点

2. 我们也可以使用非递归的方式来进行翻转链表,首先遍历链表,使用一个指针pre记录当前节点的前一个节点,使用当前节点的next指向前一个节点pre,即下一个元素的指针next指向前一个元素pre那么就实现了链表的翻转

这里特别要注意的是pre.next不能赋值为空,当第一个元素的时候倒是没有关系,但是在循环后面的元素pre是有指向的,指向的是前一个元素,假如你再修改的话那么会导致前面形成的链表会断掉,最后只会剩下两个元素,所以不能够写下面的pre.next = null;这句代码,假如遍历是从第二个元素开始的那么应该在循环之前把第一个pre的next置为空即可

while(p != null){
            temp = p.next;

            //pre.next = null;
            p.next = pre;
            pre = p;
            p = temp;
        }

3. 具体的代码如下:

public class Main {
    private static class ListNode{
        private ListNode next;
        private Object value;
        public ListNode(Object value) {
            super();
            this.value = value;
        }
    }
    
    public static void main(String[] args){
        int arr[] = {0, 6, 6, 7, 3, 3, 5, 3, 8, 9, 10};
        //int arr[] = {0, 1};
        ListNode head = new ListNode(arr[0]);
        ListNode p = head;
        for(int i = 1; i < arr.length; i++){
            p.next = new ListNode(arr[i]);
            p = p.next;
        }
        p = head;
        while(p != null){
            System.out.print(p.value+ " ");
            p = p.next;
        }
        System.out.print("\n");
        p = reverseLinkedList(head);
        while(p != null){
            System.out.print(p.value+ " ");
            p = p.next;
        }
    }

    private static ListNode reverseLinkedList(ListNode node){
        ListNode p = node.next;
        ListNode pre = node;
        pre.next = null;
        ListNode temp;
        while(p != null){
            temp = p.next;
            p.next = pre;
            pre = p;
            p = temp;
        }
        return pre;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39445165/article/details/84700757