学习单链表的使用
此处用到空节点,作为一种提取所用节点,区别废节点的工具,可以按照条件筛选节点。
头节点作为一个链表的基准,很多时候不好先对头动手,此时如果可以另外选择一个空基准的话,不失为一个好的选择,这个举例在此处可能不太合理,哈哈哈
package demo0716;
public class Single_Node {
Node head = null;
/**
* 单链表 节点 实体类定义
*/
class Node {
//属性
public int data;
public Node next;
//方法
public Node(int data) {
this.data = data;
}
}
/**
* 尾插法
*/
public void addlast(int data) {
Node cur = this.head;
Node newnode = new Node(data);
if (head == null) {
head = newnode;
} else {
while (cur.next != null) {
cur = cur.next;
}
cur.next = newnode;
}
}
/**
* 打印链表
*/
public void display() {
Node cur = this.head;
if (cur == null) {
return;
}
while (cur != null) {
System.out.print(cur.data + " ");
cur = cur.next;
}
}
/**
* 带返回参数打印链表
*/
public void display2(Node head) {
Node cur = head;
if (cur == null) {
return;
}
while (cur != null) {
System.out.print(cur.data + " ");
cur = cur.next;
}
}
/**
* 利用空的头节点,删除链表中重复的元素
* 重复元素指的是:相邻两个元素是相同的!
* @param
*/
public Node samepoint(int data) {
Node cur = this.head;
//空头
Node emptyhead = new Node(-1);
//空头替身
Node tmp = emptyhead;
while (cur !=null) {
if (cur.next != null && cur.data == cur.next.data) {
while (cur.next != null && cur.data == cur.next.data) {
cur = cur.next;
}
cur = cur.next;
} else {
tmp.next = cur;
tmp = tmp.next;
cur = cur.next;
}
}
return emptyhead.next;
}
public static void main(String[] args) {
Single_Node demo = new Single_Node();
System.out.println("**** 尾插法 ****");
demo.addlast(1);
demo.addlast(2);
demo.addlast(2);
demo.addlast(3);
demo.addlast(4);
demo.addlast(5);
demo.display();
System.out.println();
System.out.println("**** XX法 ****");
Node same = demo.samepoint(2);
demo.display2(same);
}
}
结果如下:
是一种思路,目前这个阶段就是熟练使用,顺便积累思路的过程!