您的位置:首页 > 编程语言 > Java开发

java单链表 插入 删除 查找 链表反转

2015-05-24 00:00 204 查看
摘要: java单链表 插入 删除 查找 链表反转

/**

* Created by jinzhao .w on 2015/4/9.

*/

public class Link {

public int data;

public Link next;

public Link(int data) {

this.data = data;

}

@Override

public String toString() {

return "Link{" +

"data=" + data +

'}';

}

}

--------------------------------------------------------------------

/**

* Created by jinzhao.w on 2015/4/9.

*/

public class LinkList {

private static Link first;

public LinkList() {

this.first = null;

}

public LinkList(Link first) {

this.first = first;

}

public boolean isEmpty() {

return (first == null);

}

public void insertFirst(int id) {

Link newLink = new Link(id);

newLink.next = first;

first = newLink;

}

public Link deleteFirst() {

Link temp = first;

first = first.next;

return temp;

}

public Link getFirst(){

return first;

}

public void displayList(Link current) {

if(current==null)

current = first;

while (current != null) {

System.out.println(current.toString());

current = current.next;

}

}

public Link find(int key) {

Link current = first;

while (current.data != key) {

if (current.next == null) {

return null;

} else {

current = current.next;

}

}

return current;

}

public Link delete(int key) {

Link current = first;

Link previous = first;

while (current.data != key) {

if (current.next == null) {

return null;

} else {

previous = current;

current = current.next;

}

}

if (current == first) {

current = current.next;

} else {

previous.next = current.next;

}

return current;

}

public static void reverseLinkList(Link first) {

Link current = first;

Link next=null;

Link prev=null;

while (current!=null){

next=current.next;

current.next=prev;

prev=current;

current=next;

}

LinkList.first=prev;

}

}

---------------------------------------------------------------------

/**

* Created by jinzhao.w on 2015/4/9.

*/

public class LinkListTest {

public static void main(String[] args) {

LinkList linkList = new LinkList();

linkList.insertFirst(1);

linkList.insertFirst(2);

linkList.insertFirst(3);

linkList.insertFirst(4);

linkList.insertFirst(5);

// linkList.displayList();

// Link findLink = linkList.find(4);

// findLink.toString();

// linkList.delete(4);

LinkList.reverseLinkList(linkList.getFirst());

linkList.displayList(linkList.getFirst());

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: