链表相应操作

链表

#include <map>  
#include <cmath>  
#include <queue>  
#include <cstdio>  
#include <string>  
#include <cstring>  
#include <iostream>  
#include <algorithm> 
#include <sstream> 
#include <time.h> 
#include <vector>
#include <list>
#include <stack>
using namespace std;
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

//创建一个具有n个节点的链表,从键盘输入数据将其初始化,并返回链表的首节点指针
ListNode *createNode(int n)
{
	ListNode *pHead(0), //首节点指针 
		*pRear(0), //尾节点指针
		*pNew; //新节点指针
	int i;
	for (i = 0; i<n; i++)
	{
		pNew = new ListNode(0);
		cin >> pNew->val;
		if (0 == i)
		{
			pRear = pHead = pNew;
		}
		else
		{
			pRear->next = pNew;
		}
		pNew->next = NULL;
		pRear = pNew;
	}
	return pHead;
}

//输出链表中的内容
void printNode(ListNode *pHead)
{
	ListNode *pTemp = pHead;

	while (pTemp != NULL)
	{
		cout << pTemp->val;
		pTemp = pTemp->next;
	}
	cout << endl;
}

//查询链表中具有指定值的节点,并返回此节点指针
ListNode *searchNode(ListNode *pHead, int val)
{
	ListNode *pDest = pHead;
	while (pDest->next != NULL && pDest->val != val)
		pDest = pDest->next;
	if (pDest->val == val)
		return pDest;
	else
		return NULL;
}

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

	int a = 0, b = 0;
	int num = 0;
	ListNode *LL = l1;
	while (LL != NULL)
	{
		a += LL->val*pow(10, num);
		num++;
		LL = LL->next;
	}
	LL = l2;
	num = 0;
	while (LL != NULL)
	{
		b += LL->val*pow(10, num);
		num++;
		LL = LL->next;
	}
	int c = a + b;
	cout << c << endl;
	ListNode *out, *save(0);
	//调用前必须分配空间(指针赋值)
	out = new ListNode(0);		
	out->val = c % 10;
	save = out;
	while ((c /= 10))
	{
		ListNode *front;
		front = new ListNode(0);
		front->val = c % 10;
		save->next = front;
		save = front;
	}
	save->next = NULL;
	return out;
}
int main()
{
	int i, j, N, M;
	//m和n分别表示画布的宽度和高度,q表示画图操作的个数
	cin >> N ;		
	ListNode *P = createNode(N);
	printNode(P);
	ListNode *q = createNode(N);
	printNode(q);
	ListNode * out = addTwoNumbers(P, q);
	printNode(out);
	cin >> N >> M;
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值