合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解题思路
注意题目测试时所有链表头节点指针域不为空
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(NULL) {}
ListNode(int x) : val(x), next(NULL) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* l;
ListNode *pre,*p,*head;
head=new ListNode;
head->next=NULL;
pre=head;
//l1=l1->next;
//l2=l2->next;
while(l1&&l2)
{
p=new ListNode;
if(l1->val<l2->val)
{
p->val=l1->val;
l1=l1->next;
}
else
{
p->val=l2->val;
l2=l2->next;
}
p->next=NULL;
pre->next=p;
pre=p;
}
if(l1)
pre->next=l1;
else
pre->next=l2;
return head->next;
}
ListNode* create(int Array[],int n)
{
ListNode *p,*pre,*head;//pre保存当前节点的前驱节点,head为头节点
head=new ListNode;//创建头节点
head->next=NULL;//头节点不需要数据域
pre=head;//记录pre为head
for(int i=0;i<n;i++)
{
p=new ListNode;//新建节点
p->next=NULL;//新节点的指针域设置为null
p->val=Array[i];//数据域
pre->next=p;//前驱节点的指针域设置为当前新建系欸但的地址
pre=p;//把pre设为p,作为下个节点的前驱节点
}
return head;
}
int main()
{
int n,Array1[10],Array2[10];
ListNode *l1,*l2,*l;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>Array1[i];
}
l1=create(Array1,n);
for(int i=0;i<n;i++)
{
cin>>Array2[i];
}
l2=create(Array2,n);
l=mergeTwoLists(l1,l2);
//l=l->next;
while(l)
{
cout<<l->val<<endl;
l=l->next;
}
return 0;
}
删除排序链表中的重复元素
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
输入: 1->1->2
输出: 1->2
解题思路(参考题解)
ListNode* deleteDuplicates(ListNode* head) {
ListNode *pre,*pr;
//头结点或头结点的下一结点为空
if(!head||!head->next) return head;
pre=head;
pr=pre->next;
while(pre&&pre->next)
{
//相等时
if(pre->val==pr->val)
{
//删除结点
pre->next=pr->next;
pr=pr->next;
}
//遇到不相等的节点时,pre移动
else pre=pre->next;
}
return head;
}