使用单个how循环从给定的单个链表中打印最后第三个元素
with single how loop to print last 3rd element from given single linked list?
使用单循环,我们如何从给定的单个链表中打印最后第三个元素假设链表中有10个节点我应该找到最后3个节点?下面的代码是在开始插入一个节点,现在我怎样才能用singloop打印最后的第三个元素?请帮帮我
struct node
{
int data;
struct *next; //hold address of next node
}
void insert_begin(struct node**ptr)
{
node *temp;
temp=(struct *node) malloc(sizeof(struct node));
cout<<"enter ur data"<<endl;
cin>>temp->data;
temp->next=*ptr;
*ptr=temp;
}
int main()
{
node *head=0 // making head node or 1st node null
insert_begin(&head);
insert_begin(&head);
insert_begin(&head);
.....upto 10
}
保持三个指针:
node * prevPrev = null;
node * prev = null;
node * current = head;
用current
遍历列表,直到current->next
为空。每次迭代更新prev
和prevPrev
prevPrev = prev;
prev = current;
current = current->next;
当current->next
为null时,prevPrev
指向最后第3个元素
您可以使用两个指针*p1,*p2并初始化它们,使*p1指向列表的第一个元素,*p2指向列表的第三个元素。然后循环,直到*p2到达列表的末尾,在每次循环中将两个指针都移动到下一个元素。当*p2到达末尾时,打印*p1所指向的元素
好的,要简单地做到这一点,你可以做的是首先管理链接长度的计数器变量,即。"数"。现在:
int len = count;
*temp = ptr;
while(tmp->next != null)
{
len--;
if(len==3)
{
//you are at the last third element
// do your work and break the loop
}
else
{
temp = temp->next;
}
}
相关文章:
- 读取文件的最后一行并输入到链接列表时出错
- lower_bound()返回最后一个元素
- 从控制台中删除最后打印的元素
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 获取向量C++中第一个值和最后一个值的和
- 获取用C/C++打印的最后一个字符串
- 读取最后一行代码算法 - c++ 时出现问题
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 为什么我的最后一个 ELSE 条件无法正确执行
- Eclipse CDT:单个项目中有多个C++文件
- 为什么我们将单个或多维数组的大小声明为常量值?
- C++调用具有 *this 属性的单个帮助程序函数
- 如何在最后一步使用CryptDecrypt解决NTE_BAD_DATA
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 使用递归在单个链表中查找第n到最后一个节点
- 使用单个how循环从给定的单个链表中打印最后第三个元素