使用单个how循环从给定的单个链表中打印最后第三个元素

with single how loop to print last 3rd element from given single linked list?

本文关键字:单个 最后 元素 三个 打印 链表 循环 how      更新时间:2023-10-16

使用单循环,我们如何从给定的单个链表中打印最后第三个元素假设链表中有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为空。每次迭代更新prevprevPrev

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;
    }
}