`

Simple List with c and java

阅读更多
总结:
    从下面的代码可以看出,C中几乎所有函数都需要持有list指针,而且在使用上也十分麻烦,需要在主函数中维护头指针。sdfdf
    Java用了三个文件,ListNode.java,List.java还有一个Test.java。从下面贴出的List.java的代码可以看出,函数实现相对简单一些,不必要维护list指针,因为有对象属性存在。这里可以看出一些面向对象编程的好处。

LinkedList.c:
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>

typedef struct node_s {
	void *data; 
	struct node_s *next;
} NODE;

NODE *list_create(void *data) {
	NODE *node;
	if (!(node = malloc(sizeof(NODE)))) {
		return NULL;
	}
	node->data = data;
	node->next = NULL;
	return node;
}


NODE *list_insert_after(NODE *node, void *data) {
	NODE *newnode;
	newnode = list_create(data);
	newnode->next = node->next;
	node->next = newnode;
	return newnode;
}

NODE *list_insert_beginning(NODE *list, void *data) {
	NODE *newnode;
	newnode = list_create(data);
	newnode->next = list;
	return newnode;
}


int list_remove(NODE *list, NODE *node) {
	while (list->next && list->next != node) {
		list = list->next;
	}
	if (list->next) {
		list->next = node->next;
		free(node);
		return 0;
	} else {
		return -1;
	}
}

int list_foreach(NODE *node, int (*func)(void *)) {
	while (node) {
		if (func(node->data) != 0) return -1;
		node = node->next;
	}
	return 0;
}


NODE *list_find(NODE *node, int (*func)(void *, void *), void *data) {
	while (node) {
		if (func(node->data, data) > 0) {
			return node;
		}	
		node = node->next;
	}
	return NULL;
}

int printstring(void *s) { 
	printf("%s\n", (char *)s);
	return 0;
}


int findstring(void *listdata, void *searchdata) {
	return strcmp((char*)listdata, (char *)listdata) ? 0 : 1;
}

int main() {
	NODE *list, *second, *inserted;
	NODE *match;

	/* Create initial elements of list */
	list = list_create((void *)"First");
	second = list_insert_after(list, (void *)"second");
	list_insert_after(second, (void *)"Third");

	printf("Initail list:\n");
	list_foreach(list, printstring);
	putchar('\n');

	/* Insert one extra element in the beginning */
	list = list_insert_beginning(list, "BeforeFirst");
	printf("After list_insert_beginning():\n");
	list_foreach(list, printstring);
	putchar('\n');

	/* Insert one extra element after second */
	inserted = list_insert_after(second, "AfterSecond"); 
	printf("After list_insert_after():\n");
	list_foreach(list, printstring);
	putchar('\n');


	/* Remove the element */
	list_remove(list, inserted);
	printf("After list_remove():\n");
	list_foreach(list, printstring);
	putchar('\n');

	/* search */
	if ((match = list_find(list, findstring, "Third")) != NULL) {
		printf("Found \"Third\"\n");
	} else {
		printf("Did not find \"Third\"\n");
	}
	
	return 0;
}






List.java
package com.lingceng;

import com.lingceng.util.ListNode;

public class List {
	private ListNode root;
	private int max = 10;
	private int number;

	public List() {
		this.root = null;
		this.number = 0;
	}

	public ListNode getRoot() {
		return this.root;
	}

	public int getNumber() {
		return this.number;
	}

	public int getMax() {
		return this.max;
	}

	public void setRoot(ListNode root) {
		this.root = root;
	}

	public void insertAfter(int value) {
		ListNode tmp = new ListNode(value);
		ListNode tmp2 = this.root;

		if (this.number == this.max) {
			System.out.println("insert full list");
			return;
		}

		while (tmp2.getNext() != null) {
			tmp2 = tmp2.getNext();
		}

		tmp2.setNext(tmp);
		this.number++;
	}

	public void insertBeginning(int value) {
		ListNode tmp = new ListNode(value, this.root);

		if (this.number == this.max) {
			System.out.println("insert full list");
			return;
		}

		this.root = tmp;
		this.number++;
	}


	public void removeIndex(int n) {
		ListNode tmp = this.root;

		if (this.root == null) {
			return;
		}

		if (n == 0) {
			this.root = this.root.getNext();
			return;
		}

		for(int i = n; i > 1; i--) {
			if(tmp.getNext() == null) {
				return;
			}
			tmp = tmp.getNext();
		}

		tmp.setNext(tmp.getNext().getNext());
		this.number--;
	}

	public void removeValue(int value) {
		ListNode tmp = this.root;

		if (this.root == null) {
			return;
		}

		if (this.root.getValue() == value) {
			this.root = this.root.getNext();
			return;
		}

		while (tmp.getNext().getValue() != value) {
			tmp = tmp.getNext();
			if (tmp.getNext() == null) {
				return;
			}
		}

		tmp.setNext(tmp.getNext().getNext());
		this.number--;
	}

	@Override
	public String toString() {
		ListNode tmp = this.root;
		if (this.root == null) {
			return "Empty List";
		}
		StringBuffer sb = new StringBuffer();
		while (tmp != null) {
			sb.append(tmp.getValue());
			if (tmp.getNext() != null) {
				sb.append("->");
			}
			tmp = tmp.getNext();
		}

		return sb.toString();
	}
}



所有Java代码见附件
分享到:
评论

相关推荐

    Amazon SimpleDB JAVA API 文档详解

    ### Amazon SimpleDB JAVA API 文档详解 #### 一、引言与概述 Amazon SimpleDB 是一个高度可用且灵活的非关系型数据存储服务,适用于云端应用程序。它为开发者提供了简单的 API 接口来存储和查询数据,而无需管理...

    Java邮件开发Fundamentals of the JavaMail API

    A general familiarity with object-oriented programming concepts and the Java programming language is necessary. The Java language essentials tutorial can help. copyright 1996-2000 Magelang ...

    jna-4.2.2 官方原版下载

    Automatic conversion between C and Java strings, with customizable encoding/decoding Structure and Union arguments/return values, by reference and by value Function Pointers, (callbacks from native...

    javacv-platform-1.3.3-src

    And feel free to ask questions on the mailing list if you encounter any problems with the software! I am sure it is far from perfect... Downloads To install manually the JAR files, obtain the ...

    Java-API-1.6.rar_java 1.6api_java api 1.6 115_java doc_java-a_ja

    Java 1.6提供了SAX(Simple API for XML)、DOM(Document Object Model)和JAXB(Java Architecture for XML Binding)等API来解析、操作和生成XML文档。 12. **安全管理**: Java的权限模型在1.6中进一步完善,...

    Packt.Spring.5.0.Projects.rar

    You must have a good knowledge of Java programming and be familiar with the basics of Spring. Table of Contents Creating an Application to List World Countries with their GDP Building a Reactive ...

    scala-sbt-scala编译工具

    Continuous compilation and testing with triggered execution Packages and publishes jars Generates documentation with scaladoc Supports mixed Scala/Java projects Supports testing with ScalaCheck, specs...

    JSP Simple Examples

    One of the strong features of java is that it is follows a OOPs concept, and one of the feature of OOP in java is that, we can assign a subclass object or variable to the variable of the superclass ...

    Csharp.6.for.Programmers.6th.Edition

    including C#, C++, C, Java™, Android™ app development, iOS app development, Swift™, Visual Basic®, Python™ and Internet and web programming. Features: Use with Windows® 7, 8 or 10. Integrated...

    编程珠玑全部源代码 分享

    markovlet.c -- Letter-level markov text, simple algorithm. Appendix 3: Cost Models spacemod.cpp -- Space used by various records. timemod.c -- Table of times used by various C constructs. You may...

    XDoclet in Action

    By covering a wide range of Java technologies and providing practical examples, this book equips readers with the knowledge and skills needed to enhance productivity and streamline development ...

    Learning Kotlin by building Android Applications

    It also ensures seamless interoperability with existing Android languages like JAVA and C++, which makes it easier to learn a new language for their most favored platform. This book adopts a project...

    UE(官方下载)

    However, what happens when you're moving to a new system and you want to port your settings and customizations over along with UltraEdit? Add a webpage to your toolbar Use UltraEdit's powerful user ...

    在Java中读取xml文件

    要实现这个功能,我们需要使用Java的标准库JAXB(Java Architecture for XML Binding)或者DOM(Document Object Model)、SAX(Simple API for XML)等解析器。下面我们将详细介绍如何在Java中读取XML文件。 1. ...

    Manning - Eclipse In Action.pdf

    - **Appendix C: Plug-in Extension Points**: List of available extension points for extending Eclipse plug-ins. - **Appendix D: Introduction to SWT**: Overview of Standard Widget Toolkit (SWT), a ...

    Addison.Wesley.C++.by.Dissection.2002.pdf

    - **C++ Compared with Java:** Compares C++ with Java, highlighting differences in syntax and features. ### Chapter 2: Native Types and Statements Chapter 2 delves deeper into the native types and ...

    一个java正则表达式工具类源代码.zip(内含Regexp.java文件)

    * [abc] a, b, or c (simple class) [abc] a, b, 或 c (简单字符串) * [^abc] Any character except a, b, or c (negation) [^abc] 除了 a, b, 或 c 之外的任意字符(否定) * [a-zA-Z] a ...

    Programming.Concepts.in.Cplusplus.1499044836

    Other books in the series use languages like Java and Python, but all focus on concepts and not on any particular language. The presentation of the material is the same in each language, and much of ...

Global site tag (gtag.js) - Google Analytics