如何构建链表

构建链表

#include

using namespace std;
struct Node{
	int data;
	Node *next;
};
int main()
{
	Node *head, *p,*q;
	int n;
	head = NULL;
	cin >> n;
	int t;
	for(int i = 0; i < n; i++)
	{ 
	    cin >> t;
	    p = new Node;
	    p->data = t;
	    p->next = NULL;
	    if(head == NULL){
	    	head = p;
		}
		else {
			q->next = p;
		}
		q = p;
		
	}
	Node *x;
	x = head; //切记; 
	while(x != NULL)
	{
		cout<<x->data<<' ';
		x = x->next;
	}
	return 0;
}

你可能感兴趣的:(数据结构,链表)