Java implementation of a single linked list, features have inserts, deletes, traversal.

Source: Internet
Author: User


public class Code {
private int data;
Private Code Next;
public int GetData () {
return data;
}
public void SetData (int data) {
This.data = data;
}
Public Code GetNext () {
return to Next;
}
public void Setnext (Code next) {
This.next = Next;
}
}


public class List {
Public Code head;
List ()
{
This.head=new Code ();
Head.setdata (0);
}
List (int n)
{
This.head=new Code ();
Code p,temp;
P=head;
for (int i=0;i<n;i++)
{
Temp=new Code ();
Temp.setdata (i+1);
P.setnext (temp);
P=p.getnext ();
}
Head.setdata (n);
}
Traversing nodes
public void Rlist ()
{
Code temp;
Temp=head;
while (Temp.getnext ()!=null)
{
Temp=temp.getnext ();
System.out.println (Temp.getdata ());
}
}
Delete a node
public void Dcode (int n)
{
if (N>head.getdata ()) {
SYSTEM.OUT.PRINTLN ("Cannot find the first" +n+ "Node");
Return
}
Code temp;
Temp=head;
for (int i=0;i<n-1;i++)
{
Temp=temp.getnext ();
}
Temp.setnext (Temp.getnext (). GetNext ());
Head.setdata (Head.getdata ()-1);
}
Insert Node
public void Icode (int n,int D)
{
if (N>head.getdata () +1) {
SYSTEM.OUT.PRINTLN ("Cannot find the first" +n+ "Node");
Return
}
Code p=new Code ();
P.setdata (d);
Code temp;
Temp=head;
for (int i=0;i<n-1;i++)
{
Temp=temp.getnext ();
}
P.setnext (Temp.getnext ());
Temp.setnext (P);
}
public static void Main (String args[])
{
List L=new list (5);
L.rlist ();
L.icode (3,8);
L.rlist ();
L.dcode (4);
L.rlist ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.