剑指offer常用链表操作

   剑指offer中有很多的关于链表的操作,现总结如下:(对于单向链表,由于不能回溯,故比双向指针要更稍微复杂些)

#include <iostream>
#include <string>
using namespace std;
//单链表的数据结构
struct List_node
{
	char data;
	List_node *next;
};
class List_solution
{
public:
	//创建链表
	List_node* create_List()
	{
		List_node *list_head=new List_node;
		list_head->data='#';
		list_head->next=NULL;
		char data;
		List_node *tem=list_head;
		int i=1;
		while(true)
		{
			cout<<"请输入下第"<<i<<"个结点的数据值:"<<endl;
			cin>>data;
			if(data=='#')
				break;
			else
			{
				List_node* p=new List_node;
				p->data=data;
				tem->next=p;
				p->next=NULL;
				tem=p;
			}
			i++;
		}
		return list_head;
	}
	void print_List(List_node * list_head)
	{
		while(list_head->next!=nullptr)
		{
			cout<<list_head->next->data<<"-->";
			list_head=list_head->next;
		}
		cout<<"NULL"<<endl;
	}

	//翻转链表,由于是单向链表,不能往前回溯,有不能让链表断裂,所以要维护三个指针
	List_node* reverse(List_node *listhead)
	{
		if(listhead==NULL)
			return NULL;
		List_node* pre=NULL;
		List_node* pnext=NULL;
		List_node* pcurrent=listhead->next; //开始指向第一个元素
		while(pcurrent!=NULL)
		{
			pnext=pcurrent->next; //保存当前结点的下一个元素
			pcurrent->next=pre; //把当前的结点的下一个结点指向上一个结点,实现反向
			pre=pcurrent;   //把上一个结点设为当前结点
			pcurrent=pnext;  //把当前结点指向下一个结点
		}
		listhead->next=pre;
		return listhead;
	}

	//合并两个排序好的链表
	List_node* merge(List_node* listhead1,List_node* listhead2)
	{
		List_node* p1=listhead1->next;
		List_node* p2=listhead2->next;
		//首先考虑特殊情况
		if(p1==nullptr)   //为空
			return listhead2;
		else if(p2==nullptr)
			return listhead1;	

		List_node* tem=listhead1;
		while(p1!=nullptr&&p2!=nullptr)
		{
			if(p1->data<p2->data)  //listhead1的值比较小,一直后退直到大于listhead2结点的值
			{
				while(p1!=nullptr&&p1->data<p2->data)
				{
					tem->next=p1;
					tem=tem->next;
					p1=p1->next;
				}
			}
			else if(p2->data<p1->data)//listhead2的值比较小
			{
				while(p2!=nullptr&&p2->data<p1->data)
				{
					tem->next=p2;
					tem=tem->next;
					p2=p2->next;
				}
			}
		}
		tem->next=(p1==nullptr)?p2:p1;     //最后肯定有一个先为空,直接把还非为空的指针接在后面
		
		return listhead1;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	List_solution list;
	List_node *list1=list.create_List();
	List_node *list2=list.create_List();
	list.print_List(list.merge(list1,list2));
	//List_node *head=list.create_List();
	//list.print_List(head);
	//list.print_List(list.reverse(head));
	return 0;
}

总结:在链表的操作中往往会涉及到很多的指针操作,所以要特别注意出现空指针的情况,还有什么时候到达边界,防止可能因为一些特殊的输入导致程序崩溃。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值