反转链表 [英] Reversing a linked list

查看:104
本文介绍了反转链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不使用递归的情况下扭转链接列表时出现问题。

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 linked list even though the function looks good It goes on to print the linked list in the same way as it did earlier.

有人可以帮我理解是什么这里错了??

Can someone help me understand what is wrong here??

class link {
    int data;
    public link nextlink;

    link(int d1) {
        data = d1;
    }
}

class List{

    link head;
    link revhead;

    List(){
        head = null;
    }

    boolean isEmpty(link head) {
       return head==null;
    }

    void insert(int d1) {
        link templink = new link(d1);
        templink.nextlink = head;
        head = templink;
    }

    void printlist(){
        link head1 = head;
        while(!isEmpty(head1)) {
            System.out.print(head1.data + " ");
            head1 = head1.nextlink;
        }
        System.out.println();
    }

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

}

public class LinkedList {

    public static void main(String[] args) {

        List list1 = new List();

        list1.insert(10);
        list1.insert(20);
        list1.insert(30);
        list1.insert(40);
        list1.insert(50);
        list1.printlist();
        list1.reverse();
        list1.printlist();
     }
}


推荐答案

那里你的代码中有两个问题。一:你检查isEmpty(head)你应该检查的位置!isEmpty(head)。第二:当你解决第一个问题时,当循环终止时,'head'变为null。

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;
    }

}

这篇关于反转链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆