用java写一个 addFirst(E e)将指定元素插入此列表的开头的方法
时间: 2023-06-01 10:04:41 浏览: 59
以下是使用Java编写的addFirst(E e)方法的示例:
```
public void addFirst(E e) {
Node<E> newNode = new Node<>(e); // 创建一个新节点
newNode.next = head; // 将新节点的下一个节点设置为当前头节点
head = newNode; // 将头节点设置为新节点
if (tail == null) { // 如果列表为空,则将尾节点也设置为新节点
tail = newNode;
}
size++; // 增加列表大小
}
```
该方法中使用了一个泛型类Node,其定义如下:
```
private static class Node<E> {
E element;
Node<E> next;
public Node(E element) {
this.element = element;
this.next = null;
}
}
```
该类表示一个节点,包含一个元素和指向下一个节点的引用。在addFirst方法中,我们创建一个新节点,并将其next引用设置为当前头节点,然后将头节点设置为新节点。如果列表为空,则将尾节点也设置为新节点。最后,我们增加列表大小。
相关问题
使用java实现链表的代码封装,要求包括提取元素,插入元素,删除元素,寻找元素,写到一个文件里面,使用静态类
以下是使用Java实现链表的代码封装,包括提取元素、插入元素、删除元素、寻找元素:
```java
public class LinkedList<E> {
private Node<E> head;
private int size;
public LinkedList() {
head = null;
size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void addFirst(E element) {
head = new Node<>(element, head);
size++;
}
public void addLast(E element) {
if (isEmpty()) {
addFirst(element);
} else {
Node<E> current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(new Node<>(element, null));
size++;
}
}
public E getFirst() {
if (isEmpty()) {
throw new NoSuchElementException("List is empty");
}
return head.getElement();
}
public E getLast() {
if (isEmpty()) {
throw new NoSuchElementException("List is empty");
}
Node<E> current = head;
while (current.getNext() != null) {
current = current.getNext();
}
return current.getElement();
}
public E removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException("List is empty");
}
E element = head.getElement();
head = head.getNext();
size--;
return element;
}
public E removeLast() {
if (isEmpty()) {
throw new NoSuchElementException("List is empty");
}
if (size() == 1) {
return removeFirst();
}
Node<E> current = head;
while (current.getNext().getNext() != null) {
current = current.getNext();
}
E element = current.getNext().getElement();
current.setNext(null);
size--;
return element;
}
public boolean contains(E element) {
Node<E> current = head;
while (current != null) {
if (element.equals(current.getElement())) {
return true;
}
current = current.getNext();
}
return false;
}
public void add(int index, E element) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Invalid index");
}
if (index == 0) {
addFirst(element);
} else {
Node<E> current = head;
for (int i = 0; i < index - 1; i++) {
current = current.getNext();
}
current.setNext(new Node<>(element, current.getNext()));
size++;
}
}
public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Invalid index");
}
Node<E> current = head;
for (int i = 0; i < index; i++) {
current = current.getNext();
}
return current.getElement();
}
public E remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Invalid index");
}
if (index == 0) {
return removeFirst();
} else {
Node<E> current = head;
for (int i = 0; i < index - 1; i++) {
current = current.getNext();
}
E element = current.getNext().getElement();
current.setNext(current.getNext().getNext());
size--;
return element;
}
}
public int indexOf(E element) {
Node<E> current = head;
int index = 0;
while (current != null) {
if (element.equals(current.getElement())) {
return index;
}
current = current.getNext();
index++;
}
return -1;
}
private static class Node<E> {
private E element;
private Node<E> next;
public Node(E element, Node<E> next) {
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
}
```
在这个实现中,我们使用了一个内部静态类`Node`来表示链表中的每个节点。这个类包含一个元素属性和一个指向下一个节点的指针属性。链表本身包含一个头节点属性和一个大小属性,用来记录链表中节点的数量。我们实现了以下方法:
- `size()`:返回链表中节点的数量。
- `isEmpty()`:检查链表是否为空。
- `addFirst(element)`:在链表的开头插入一个新节点。
- `addLast(element)`:在链表的末尾插入一个新节点。
- `getFirst()`:返回链表的第一个节点的元素。
- `getLast()`:返回链表的最后一个节点的元素。
- `removeFirst()`:删除链表中的第一个节点,并返回该节点的元素。
- `removeLast()`:删除链表中的最后一个节点,并返回该节点的元素。
- `contains(element)`:检查链表中是否包含给定的元素。
- `add(index, element)`:在链表的指定位置插入一个新节点。
- `get(index)`:返回链表中指定位置的节点的元素。
- `remove(index)`:删除链表中指定位置的节点,并返回该节点的元素。
- `indexOf(element)`:返回链表中给定元素的第一个出现位置的索引。
以上实现可以被封装到一个名为`LinkedList`的类中,该类使用泛型来允许存储任何类型的元素。
用Java编程:写一个贪吃蛇小游戏
抱歉,作为AI语言模型,我无法编写和运行Java程序。但是,我可以为您提供以下Java代码作为参考,以编写贪吃蛇小游戏:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class SnakeGame extends JFrame implements ActionListener {
//定义游戏区域的大小
private final int WIDTH = 600;
private final int HEIGHT = 600;
//定义每个方块的大小
private final int BLOCKSIZE = 20;
//定义游戏区域中的方块数
private final int BLOCKS = 30;
//定义蛇的初始长度
private final int INITLENGTH = 3;
//定义蛇的方向
private final int RIGHT = 0;
private final int LEFT = 1;
private final int UP = 2;
private final int DOWN = 3;
//定义游戏用的计时器
private Timer timer;
//定义游戏区域中的蛇
private Snake snake;
//定义游戏区域中的食物
private Food food;
//定义游戏是否结束
private boolean gameOver;
public SnakeGame() {
//设置窗口的大小和标题
setSize(WIDTH, HEIGHT);
setTitle("贪吃蛇小游戏");
//设置窗口的关闭方式
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//创建游戏区域中的蛇和食物
snake = new Snake(INITLENGTH);
food = new Food();
//创建游戏用的计时器
timer = new Timer(100, this);
//启动计时器
timer.start();
//将游戏区域设置为可见
setVisible(true);
}
public void paint(Graphics g) {
//调用父类的paint方法
super.paint(g);
//绘制游戏区域中的蛇和食物
snake.paint(g);
food.paint(g);
}
public void actionPerformed(ActionEvent e) {
//判断游戏是否结束
if (gameOver) {
//停止计时器
timer.stop();
//弹出游戏结束的提示框
JOptionPane.showMessageDialog(this, "游戏结束");
} else {
//让蛇移动
snake.move();
//判断蛇是否吃到了食物
if (snake.eat(food)) {
//重新生成食物
food.generate();
}
//判断蛇是否撞墙或自己的身体
if (snake.hitWall() || snake.hitBody()) {
//游戏结束
gameOver = true;
}
//重新绘制游戏区域
repaint();
}
}
private class Snake {
//蛇的身体,用一个链表来表示
private LinkedList<Point> body;
//蛇的方向
private int direction;
public Snake(int length) {
//创建蛇的身体
body = new LinkedList<Point>();
for (int i = 0; i < length; i++) {
body.add(new Point(BLOCKS / 2 - i, BLOCKS / 2));
}
//设置蛇的方向为右
direction = RIGHT;
}
public void paint(Graphics g) {
//绘制蛇的身体
for (Point p : body) {
g.fillRect(p.x * BLOCKSIZE, p.y * BLOCKSIZE, BLOCKSIZE, BLOCKSIZE);
}
}
public void move() {
//获得蛇头的位置
Point head = body.getFirst();
//根据方向移动蛇头
if (direction == RIGHT) {
head = new Point(head.x + 1, head.y);
} else if (direction == LEFT) {
head = new Point(head.x - 1, head.y);
} else if (direction == UP) {
head = new Point(head.x, head.y - 1);
} else if (direction == DOWN) {
head = new Point(head.x, head.y + 1);
}
//将新的蛇头插入到链表的开头
body.addFirst(head);
//删除链表的最后一个元素,即蛇尾
body.removeLast();
}
public boolean eat(Food food) {
//判断蛇是否吃到了食物
if (body.getFirst().equals(food.getPosition())) {
//将食物添加到链表的开头
body.addFirst(food.getPosition());
return true;
} else {
return false;
}
}
public boolean hitWall() {
//判断蛇是否撞墙
Point head = body.getFirst();
if (head.x < 0 || head.x >= BLOCKS || head.y < 0 || head.y >= BLOCKS) {
return true;
} else {
return false;
}
}
public boolean hitBody() {
//判断蛇是否撞到自己的身体
Point head = body.getFirst();
for (int i = 1; i < body.size(); i++) {
if (head.equals(body.get(i))) {
return true;
}
}
return false;
}
public void setDirection(int direction) {
//设置蛇的方向
this.direction = direction;
}
}
private class Food {
//食物的位置
private Point position;
public Food() {
//随机生成食物的位置
generate();
}
public void paint(Graphics g) {
//绘制食物
g.setColor(Color.RED);
g.fillRect(position.x * BLOCKSIZE, position.y * BLOCKSIZE, BLOCKSIZE, BLOCKSIZE);
}
public void generate() {
//随机生成食物的位置
Random rand = new Random();
int x = rand.nextInt(BLOCKS);
int y = rand.nextInt(BLOCKS);
position = new Point(x, y);
}
public Point getPosition() {
//返回食物的位置
return position;
}
}
public static void main(String[] args) {
//创建游戏对象
new SnakeGame();
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)