数组中的逆序


点击打开链接

问题

因为想换种结构,想用链表来解决,但是结果打印不出来,无限循环

package sort;

import java.util.*;

import org.junit.Test;

public class AntiOrder {
    public int count(int[] A, int n) {
    	int num = 0;
    	Node root = createLinkList(A);
    	Node cur;
    	while(root.next!=null) {
    		cur = root;
    		while(cur.next!=null) {
    			if(cur.a<cur.next.a)num++;
    		}
    		root = root.next;
    	}
    	return num;
    }
    
    public Node createLinkList(int[] A) {
    	Node root = new Node(A[A.length-1]);
    	Node cur = root;
    	for (int i = A.length-2; i >=0; i--) {
			cur.next = new Node(A[i]);
			cur = cur.next;
		}
    	return root;
    }
    
    public class Node{
    	int a;
    	Node next;
    	public Node(int a) {
    		this.a = a;
    	}
    }
    @Test
    public void test() {
    	int[] a = {1,2,3,4,5,6,7,0};
    	int count = count(a, 8);
    	System.out.println("count="+8);
    }
}

后来还是用for循环比较简单,还是不要装逼了

 public int count(int[] A, int n) {
    	int num = 0;
    	for (int i = 1; i < n; i++) {
			for (int j = i-1; j >=0; j--) {
				if(A[i]<A[j]) {
					num++;
				}
			}
		}
    	return num;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值