Reversing a linked list

前端 未结 5 1013
萌比男神i
萌比男神i 2021-01-17 06:48

Problem in Reversing a linked list without using recursion.

I used this method, but when i try and run this back home, I am not able to print the reverse of the lin

5条回答
  •  鱼传尺愫
    2021-01-17 07:24

    There are two problems in your code. One: you check for isEmpty(head) where as you should check for !isEmpty(head). Second: when you fix first problem, then 'head' becomes null when loop terminates.

    The correct code with fix for above two problems:

    void reverse() {
        link previous = null, temp = null;
        while (!isEmpty(head)) {
            temp = head.nextlink;
            head.nextlink = previous;
            previous = head;
            if (temp == null) {
               break;
            }
            head = temp;
        }
    
    }
    

提交回复
热议问题