将元素插入已排序的链接列表中

时间:2015-05-23 23:01:35

标签: java linked-list

我正在创建一个函数,该元素以正确的顺序将元素插入到链表中,而不依赖于列表。这是我的代码:

public void insert(E e) {
    if (e == null)
        throw new NullPointerException();

    if (head == null) {
        head = new Node(e, null);
        count++;
    } else {
        Node current = head;

        for (current = head; current != null ;){
            if(current.item.compareTo(e) > 0){
                Node temp = current;
                current = new Node(e, null);
                current.next = temp;
                break;
            }else{
                current = current.next;
            }
        }
    }   
}

我不确定什么是出错但是当我把它打印出来时,它只打印出第一个元素。我不知道链接到头节点?我希望它如此,如果它通过列表查看,一旦它找到大于它的项目,它需要该点,较大的项目会碰到下一个。已在列表外部创建链接列表构造函数。

1 个答案:

答案 0 :(得分:0)

当您在列表中插入新元素时,不会设置前一个元素的if(current.item.compareTo(e) > 0){ Node temp = current; current = new Node(e, null); current.next = temp; break; }else \\... 引用:

next

因此,第一个列表元素的null将始终指向false,实际上除了第一个元素外,列表为空。

如果列表不为空,并且每个列表元素的条件为if(current.item.compareTo(e) > 0){ ,您甚至都不会尝试插入元素:

CGRect inputExtent = [self.inputImage extent];
CIVector *extent = [CIVector vectorWithX:inputExtent.origin.x
                                       Y:inputExtent.origin.y
                                       Z:inputExtent.size.width
                                       W:inputExtent.size.height];
CIImage* inputAverage = [CIFilter filterWithName:@"CIAreaAverage" keysAndValues:@"inputImage", self.inputImage, @"inputExtent", extent, nil].outputImage;

//CIImage* inputAverage = [self.inputImage imageByApplyingFilter:@"CIAreaMinimum" withInputParameters:@{@"inputImage" : inputImage, @"inputExtent" : extent}];
EAGLContext *myEAGLContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
NSDictionary *options = @{ kCIContextWorkingColorSpace : [NSNull null] };
CIContext *myContext = [CIContext contextWithEAGLContext:myEAGLContext options:options];

size_t rowBytes = 32 ; // ARGB has 4 components
uint8_t byteBuffer[rowBytes]; // Buffer to render into

[myContext render:inputAverage toBitmap:byteBuffer rowBytes:rowBytes bounds:[inputAverage extent] format:kCIFormatRGBA8 colorSpace:nil];

const uint8_t* pixel = &byteBuffer[0];
float red   = pixel[0] / 255.0;
float green = pixel[1] / 255.0;
float blue  = pixel[2] / 255.0;
NSLog(@"%f, %f, %f\n", red, green, blue);


return outputImage;
}
@end