将一个混有字母字符和数字字符的单链表分拆为字母字符链表和数字字符链表
思路:创建三个空链表list(原链表),numlist(数字链表),letterlist(字母链表),构造拆分方法,将含有字母字符和数字字符的原链表list拆分,依次判断节点,将数字节点插入数字链表numlist,字母节点插入字母链表letterlist。
代码如下:
//创建节点类 Create Node Class
class Node<E> {
char data;
Node<E> next;
public Node(){
this.next = null;
}
public Node(char data){
this.data = data;
this.next = null;
}
}
public class Charlinklist<E> {
Node head;
public Charlinklist(){
head = new Node();
}
//尾插法插入 Tail insertion
public void TailPlug(Node head,char data){
Node node = new Node(data);
while(head != null){
//当下一个节点为空时,插入新节点,结束循环 When the next node is empty, insert a new node to end the cycle
if(head.next == null){
head.next = node;
break;
}
//当下一个节点不为空时,向后移动 Move backward when the next node is not empty
else{
head = head.next;
}
}
}
//打印链表 Print Linked List
public void Print(Node head){
head = head.next;
while(head != null){
System.out.print(head.data + " ");
head = head.next;
}
System.out.println();
}
//分类,将原链表分为数字链表和字母链表 Classify the original list into numerical list and alphabetic list
public void Sort(Node head,Charlinklist numlist,Charlinklist letterlist){
head = head.next;
while(head != null){
//如果该节点为字母字符,插入字母链表letterlist If the node is an alphabetic character, insert the letter list
if((head.data >= 'a' && head.data <= 'z') || (head.data >= 'A' && head.data <= 'Z') ){
letterlist.TailPlug(letterlist.head,head.data);
}else{
//不为字母字符,插入数字链表numlist Not an alphabetic character, insert numlist
numlist.TailPlug(numlist.head,head.data);
}
head = head.next;
}
}
public static void main(String[] args) {
char[] arr = {'a','2','s','F','0','6','e','3','1','7','l','K','9','g','h','A','p'};
Charlinklist list = new Charlinklist();
Charlinklist numlist = new Charlinklist();
Charlinklist letterlist = new Charlinklist();
//用arr初始化原链表list Initialize the original linked list with arr
for(int curpos=0;curpos < arr.length;curpos ++){
list.TailPlug(list.head,arr[curpos]);
}
System.out.println("原链表:");
list.Print(list.head);
list.Sort(list.head,numlist,letterlist);//使用分类方法 Use classification method
System.out.println("字母字符链表:");
letterlist.Print(letterlist.head);
System.out.println("数字字符链表:");
numlist.Print(numlist.head);
}
}
拆分结果:
原链表:
a 2 s F 0 6 e 3 1 7 l K 9 g h A p
字母字符链表:
a s F e l K g h A p
数字字符链表:
2 0 6 3 1 7 9