初识数据结构之单链表——Java语言

import java.util.Scanner;

public class LinkList{
	ListNode H = new ListNode(0);
	/**
	 *尾插法创建链表
	 */
	public void creatLinkList(){
		ListNode first = H;
		Scanner sc = new Scanner(System.in);
		System.out.print("输入结点的数据:");
		int x = sc.nextInt();
		while(x != -1)
		{
			ListNode q = new ListNode(x);
			first.next = q;
			first = q; //first指向新的尾结点
			x = sc.nextInt();
		}
	}
	
	/**
	 *求表长
	 */
	public int length(){
		ListNode first = H.next;
		int length = 0;
		while(first != null)
		{
			length++;
			first = first.next;
		}
		return length;
	}
	
	/**
	 *按序号查找
	*/
	public ListNode get_pos(int x){
		ListNode first = H.next;
		int pos = 0;
		while(first != null && pos < x - 1)
		{
			first = first.next;
			pos++;
		}
		if(pos == x - 1)
			return first;
		return null;
	}
	
	/**
	 *按值查找
	 */
	public ListNode get_val(int x){
		ListNode first = H.next;
		while(first != null && first.data != x)
		{
		    first = first.next;
		}
		if(first.data == x)
		    return first;
		return null;
	 }
	 
	 /**
	  *指定位置插入x
	  */
	public void insert(int pos,int x){
		ListNode p = get_pos(pos - 1); 
		if(p == null)
		{
			System.out.println("位置错误");
		}else{
			ListNode q = new ListNode(x);
			q.next = p.next;
			p.next = q;
		}	  
	}
	  
	/**
     *删除x
    */
	public void remove(int x){
		ListNode p = get_val(x);
		if(p == null)
		{
			System.out.println("元素不存在");;
		}else{
			ListNode q = H.next;
			while(q.next != p)
				q = q.next;
			q.next = p.next;
		}
	}
	/**
	 *遍历链表
	 */
	public void printLinkList(){
		ListNode first = H.next;
		while(first != null)
		{
			if(first.next == null)
				System.out.println(first.data);
			else
				System.out.print(first.data + "->");
			first = first.next;	
		}
	} 
	public static void main(String[] args)
	{
		LinkList L = new LinkList();
		L.creatLinkList();
		
		System.out.print("创建的链表为:");
		L.printLinkList();
		System.out.printf("表长:%d\n",L.length());
		
		L.insert(2,20);
		System.out.print("插入元素后的链表为:");
		L.printLinkList();
		
	    L.remove(99);
		System.out.print("删除元素后的链表为:");
		L.printLinkList();
	}
}
class ListNode{
	int data;
	ListNode next;
	ListNode(int data){
		this.data = data;
	}
	ListNode(int data,ListNode next){
		this.data = data;
		this.next = next;
	}
	
}

结果展示:
在这里插入图片描述
                      
                                               ——越努力越幸运。

猜你喜欢

转载自blog.csdn.net/weixin_43574957/article/details/84889198
今日推荐