算法刷题2(C++)链表遍历算法

  • A+
所属分类:C++

算法框架

框架1

void traverse(ListNode * phead)
{
     
    for(ListNode *p=head;p!=NULL;p=p->next)
    {
        //迭代访问p->val;
    }

}

void traverse(ListNode * phead)
{
     ListNode *p=head;
   
     while(p!=NULL)
    {
        //迭代访问p->val;
        p=p->next;
    }

}

框架2
void traverse(ListNode * phead)
{
   if(head==NULL) return;
   //访问phead->val;
   traverse(phead->next);
}

C++:

#include <iostream>
 
#include <cstdio>

using namespace std;
struct ListNode{
  int val;
  ListNode * next;
};
void Listpushback(ListNode ** pphead,int x)
{
	ListNode * newnode= new ListNode{x,NULL};
	if(*pphead ==NULL)
	{
		*pphead=newnode;
	}
	else{
		ListNode *tail = *pphead;
		while(tail->next!=NULL)
		{
			tail= tail->next;
		}
		tail->next = newnode;
	}
}
void traverse(ListNode *phead)
{

	for(ListNode * p=phead;p!=NULL;p=p->next)
	{
       cout<<"p:"<<p->val<<endl;
	}
}

void traverse1(ListNode *phead)
{
	ListNode * p=phead;
	while(p!=NULL)
	{
		
       cout<<"p:"<<p->val<<endl;
	   p=p->next;
	}
}
void traverse2(ListNode *phead)
{
	//ListNode * p=phead;
	if(phead==NULL) return;
	cout<<"p:"<<phead->val<<endl;
    traverse2(phead->next);
}

int main(int argc, char * argv[])
{

ListNode *phead=NULL;
Listpushback(&phead,1);
Listpushback(&phead,2);
Listpushback(&phead,3); 
traverse(phead);
cout<<"---------------"<<endl;
traverse1(phead);
cout<<"---------------"<<endl;
traverse2(phead);
return 0;

}

w3cjava

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: