数据结构基础知识一——链表

链表

1.逻辑上有前后顺序
2.不保证逻辑前后顺序元素挨着

以下介绍几个最基础的链表操作:
首先定义Node类:

class Node{
	public int value;
	public Node next;
	
	public Node(int value){
		this.value = value;
		this.next = null;
	}
}

一、插入

链表的遍历
public static void displayLinkedList(Node head){
		for(Node cur = head ; cur != null; cur = cur.next){
			System.out.printf("%d -->",cur.value);
		}
		System.out.println("null")
	}
头插
  1. 创建新节点
  2. 新节点的next = 原头结点
  3. 更新头结点为新结点:此时要将新节点作为一个返回值,不可以把newNode赋值给head,因为head是形参,修改时不会对实参有影响。
public static Node pushFront(Node head, int value){
		Node newNode = new Node(value);
		newNode.next = head;
		return newNode;
	}

空的链表:一个节点都没有

尾插

分情况讨论:链表中有元素和链表中无元素

  1. 空链表尾插:视为头插
  2. 非空链表尾插:
    (1)创建新节点
    (2)找到链表中最后一个节点,将最后一个节点的next指向新节点
public static Node getLast(Node head){
		Node cur = head;
		while(cur.next != null ){
			cur = cur.next;
		}
		return cur;
	}
	public static Node pushBack(Node head, int value){
		if(head == null){
			return pushFront(head,value);   //链表为空
		}else{
			Node newNode = new Node(value);  //链表不为空
			Node last = getLast(head);
			last.next = newNode;
			return head;
		}
		
	}

二、删除

头删
  1. 如果链表为空,返回null
  2. 如果链表不为空,将头节点改为原本头节点的next节点
public static Node popFront(Node head){
		if (head == null){
			System.out.printf("参数不合法%n");
			return null;
		}
		return head.next;
	}
尾删
  1. 如果链表为空报错,如果链表只有一个结点直接返回null
  2. 如果链表不为空,找到链表中倒数第二个结点,将倒数第二个结点next置为null
public static Node getLastLast(Node head){
		Node cur = head;
		while(cur.next.next != null){
			cur = cur.next;
		}
		return cur;
	}
	public static Node popBack(Node head){
		if (head == null){
			System.out.printf("参数不合法%n");
			return null;
		}
		if (head.next == null){
			return null;
		}else {
			Node lastLast = getLastLast(head);
			lastLast.next = null;
			return head;
		}
		
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值