输入描述:
输入数据一个字符串,包括字母,数字等。
输出描述:
输出首先出现三次的那个英文字符
示例1
输入
Have you ever gone shopping and
输出
e
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str);
char c[256] = {0};
for (unsigned int i = 0; i < str.length(); i++)
{
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) //英文字符
{
c[str[i]]++; //出现次数,初始为0,出现一次+1
if (c[str[i]] == 3)
{
cout << str[i] << endl;
break;
}
}
}
return 0;
}
2.单链表逆序
用递归实现
Node* Reverse(Node* head)
{
Node *newHead;
if ((head == NULL) || (head->next == NULL))
return head;
newHead = Reverse(head->next); /*递归部分*/
head->next->next = head; /*回朔部分*/
head->next = NULL;
return newHead;
}
void printNode(Node *root)
{
while (root != NULL)
{
cout << root->data << " ";
root = root->next;
}
cout << endl;
}
int main()
{
Node* head = new Node;
head->data = -1;
head->next = NULL;
Node* q = new Node;
q = head; //尾插
for (int i = 0; i < 10; i++)
{
Node* p = new Node;
p->data = i;
p->next = NULL;
q->next=p;
q = p;
}
3.两个栈实现一个队列
void push(const T& data)
{
s1.push(data);
}
void pop()
{
if (s1.empty() && s2.empty())
{
cout << "The queue is empty";
}
if (!s2.empty())
{
s2.pop();
}
else
{
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
}
4.合并两个有序链表合并后依然有序
分别用指针指向两个链表,比较两个链表指针所指向节点的值,然后将节点取下来重新组成一个链表即可,代码如下:
ListNode Merge(ListNode* head1, ListNode* head2)
{
if (head1 == NULL)
return head2;
if (head2 == NULL)
return head1;
ListNode* newhead = NULL;
if (head1->_data < head2->_data)
{
newhead = head1;
newhead->_next=Merge(head1->_next, head2);
}
if (head1->_data>head2->data)
{
newhead = head2;
newhead->_next = Merge(head1, head2->_next);
}
}
查找链表的中间节点,但只能遍历一次链表,所以我们会想到用快慢指针来解决这个问题。定义一个快指针,每次走两步,载定义一个慢指针,每次走一步。等到快指针走到链表尾,慢指针所指向的节点就是链表的中间节点。代码如下:
ListNode* FindMidNode(ListNode* head)
{
ListNode* fast;
ListNode* slow;
fast = head;
slow = head;
while (fast&&fast->_next)
{
slow = slow->_next;
fast = fase->_next->_next;
}
retrun slow;
}
6.查找单链表倒数第K个节点,要求只能遍历一次链表
其实这个题跟上面的题很像,稍微转化一下就能想出思路。我们可以定义两个指针,一个指针先走K步,然后两个指针同时移动,等到先走的指针走到链表尾部,后走的指针所指向的节点就是倒数第K个节点。要注意考虑链表的各种情况。代码如下:
ListNode* FindKthNode(ListNode* head,int k)
{
if (head == NULL || k == 0)
return NULL;
ListNode* fast;
ListNode* slow;
fast = head;
slow = head;
for (int i = 0; i < k - 1; ++i) //要注意链表长度比K短的情况
{
if (fast->_next != NULL)
fast = fast->_next;
else retrun NULL;
}
while (fast->_next != NULL)
{
fast = fast->_next;
slow = slow->_next;
}
return slow;
}