java中如何实现链表
java中就用类来实现链表结构,每个节点都是类似的,所以next就是类本身的对象。
下面是用链表来实现一个输入字符的功能
package MyFirstPackage;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyLinkNote {
public static void main(String[] args) {
JFrame w=new JFrame();
w.setSize(600,500);
w.setLocationRelativeTo(null);
MyLinkNotePanel mlnp=new MyLinkNotePanel();
w.add(mlnp);
w.addKeyListener(mlnp);
mlnp.addKeyListener(mlnp);
w.setVisible(true);
}
}
class MyLinkNotePanel extends JPanel implements KeyListener{
Node firstNode=new Node();
Node nowNode=firstNode;
int l=0;
public void paint(Graphics g){
super.paint(g);
Node tmpNode=firstNode;
int x=0;
while(tmpNode.next!=null){
g.drawString(new Character(tmpNode.next.value).toString(), 10+x*8, 15);
tmpNode=tmpNode.next;
x++;
}
g.drawLine(10+l*8, 5, 10+l*8, 15);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int code=e.getKeyCode();
if(code>=KeyEvent.VK_A && code<=KeyEvent.VK_Z){
Node newNode=new Node();
newNode.value=e.getKeyChar();
if(nowNode.next!=null){//从中间插入字符的情况
newNode.next=nowNode.next;
}
nowNode.next=newNode;
nowNode=newNode;
l++;
}
if(code==KeyEvent.VK_LEFT){//向左移动光标
if(l>0){
l--;
Node tmNode=firstNode;
while(tmNode.next!=nowNode){
tmNode=tmNode.next;
}
nowNode=tmNode;
}
}
if(code==KeyEvent.VK_RIGHT){//向右移动光标
if(nowNode.next!=null){
l++;
nowNode=nowNode.next;
}
}
repaint();
}
@Override
public void keyReleased(KeyEvent e) {
}
}
class Node{
public char value=' ';
public Node next=null;
}
}