链表元素逆序输出

108 阅读1分钟

题目描述

读入一个字符串,将其中的字母字符链入一个线性链表,将数字字符链入另一个线性链表,其他字符丢弃。要求程序能够按与读入时相反的顺序:

(1)输出字母线性链表中的元素。

(2)输出数字线性链表中的元素。

示例

image.png

思路

将字符串中的字符放在链表里,并逆序输出,考虑使用头插法建立单链表,这样输出链表时就可以实现逆序。

具体实现

#include<bits/stdc++.h>
using namespace std;
typedef struct LNode{
	char data;
	LNode *next;
	LNode():data(0),next(NULL){}
	LNode(char x):data(x),next(NULL){}
}LNode;
int main(){
	string str;
	LNode *head1 = NULL; //定义头结点,指向字母字符 
	LNode *head2 = NULL; //定义头结点,指向数字字符 
	cin>>str; //输入字符串 
	for(int i=0; i<str.size(); i++){
		if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z')){
			if(head1==NULL){ //逆序输出:头插法建立单链表 
				head1 = new LNode(str[i]);
			}else{
				LNode *s = new LNode(str[i]);
				s->next=head1;
				head1=s; //head1的也指向了s 
			} 
		}
		if(str[i]>='0' && str[i]<='9'){ //逆序输出:头插法建立单链表 
			if(head2==NULL){
				head2 = new LNode(str[i]);
			}else{
				LNode *ss = new LNode(str[i]);
				ss->next = head2;
				head2 = ss;
			}
		} 
	}
	while(head1){ //输出存放字母的链表 
		cout<<head1->data;
		head1=head1->next;
	}
	cout<<endl; 
	while(head2){ //输出存放数字字符的链表 
		cout<<head2->data;
		head2 = head2->next;
	}
	return 0;
}


小结

考察链表基本操作,一定要熟练。