我试图找出如何删除第一个节点并将其插入到链接的末尾。到目前为止,我能够添加" Hello"的每个字符。到链表并添加了" - "在列表的末尾。我正在试图弄清楚如何在list.h上实现rotate函数。
list.h:
class list{
private:
node *head;
node *tail;
public:
list(){
head = NULL;
tail = NULL;
}
~list(){
if(head == NULL){
return;
}
node *temp = head;
while(temp != NULL){
node *next = temp ->next;
delete temp;
temp = next;
}
}
void addAtEnd(char x){
node *temp = new node(x);
node *curr = head;
if(head = NULL){
head = temp;
}else{
while(curr->next != NULL){
curr = curr->next;
}
curr ->next = temp;
}
}
bool isVowel(char ch)
{
switch (ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'Y':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
return true;
default:
return false;
}
}
void rotate(){
node *temp = head;
if(isVowel(temp->n)){
addAtEnd('-');
}
}
答案 0 :(得分:2)
要将第一个元素从单个链接列表移动到最后,您必须:
// Moves one element of a single-linked list from the front to the back
void rotate() {
if (head && head != tail ) {
node* tmp = head; // Store a reference to the first element
head = head->next; // Set the head of the list to the second element
tmp->next = nullptr; // Detach the removed element from the list
tail->next = tmp; // Link the last element to the removed element
tail = tmp; // and update the tail
}
}
http://coliru.stacked-crooked.com/a/e4d322e13ff655f7
您必须更新tail
中的addAtEnd()
才能使用它。否则,您总是必须遍历列表才能找到尾部。