- package main;
- import java.math.BigInteger;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.Hashtable;
- import java.util.LinkedHashMap;
- import java.util.LinkedList;
- import org.apache.hadoop.metrics.spi.NoEmitMetricsContext;
- public class Element {
- public static void main(String[] args) {
- Linklist list=new Linklist();
- list.Add_To_Last(5);
- list.Add_To_Last(3);
- list.Add_To_First(2);
- list.Add_To_First(7);
- list.Delete_Last();
- list.Display();
- }
- }
- class Node
- {
- public int data;
- public Node next;
- public Node(int data)
- {
- this.data=data;
- }
- public Node(){}
- }
- class Linklist
- {
- public Node head=new Node();
- public Node end;
- public void Add_To_First(int data)
- {
- Node newnode=new Node(data);
- if(head.next==null)
- {
- head.next=newnode;
- end=newnode;
- }
- else
- {
- newnode.next=head.next;
- head.next=newnode;
- }
- }
- public void Add_To_Last(int data)
- {
- Node newnode=new Node(data);
- if(head.next==null)
- {
- head.next=newnode;
- end=newnode;
- }
- else
- {
- end.next=newnode;
- end=newnode;
- }
- }
- public void Display()
- {
- Node current=head;
- while(current.next!=null)
- {
- current=current.next;
- System.out.println(current.data);
- }
- }
- public Node Delete(int data)
- {
- Node current=this.head.next;
- Node previous=this.head;
- Node result=null;
- while(current!=null)
- {
- if(current.data==data)
- {
- result=current;
- previous.next=current.next;
- break;
- }
- previous=previous.next;
- current=current.next;
- }
- return result;
- }
- public Node Delete_First()
- {
- Node result=null;
- result=this.head.next;
- this.head.next=this.head.next.next;
- return result;
- }
- public Node Delete_Last()
- {
- Node current=this.head;
- Node result=new Node();
- while(true)
- {
- current=current.next;
- if(current.next.next==null)
- {
- result=current.next;
- current.next=null;
- break;
- }
- }
- return result;
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/090720149942.html
来源: http://www.codesnippet.cn/detail/090720149942.html