Given a strictly increasing integer number of data arrangement, a given x, if x does not exist, then x is inserted, required to maintain orderly inserted. There is no action.
Input formats:
There are two input lines: the first number is the value of n, there are n represents the list of data. Followed by the number of n, n representing the data. The second line is to insert numbers.
Output formats:
Linked list data is inserted after the output, separated by spaces. End of the line can not have extra spaces.
Sample Input 1:
Here we are given a set of inputs. E.g:
5 1 3 6 9 11
4
Output Sample 1:
Given here corresponding output. E.g:
1 3 4 6 9 11
Sample Input 2:
Here we are given a set of inputs. E.g:
5 1 3 6 9 11
3
Output Sample 2:
Given here corresponding output. E.g:
1 3 6 9 11
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode* next;
} LNode, * LinkList;
void CreateList(LinkList& L, int n)
{
L = new LNode;
L->next = NULL;
LNode* p = L;
int m;
for (int i = 0; i < n; i++)
{
cin >> m;
p->next = new LNode;
p = p->next;
p->data = m;
p->next = NULL;
}
}
void InsertList(LinkList& L, int n, int x)
{
LNode* p = L;
if (p-> next == NULL) // this case the list is empty directly into the node
{
LNode* q = new LNode;
q->data = x;
q->next = NULL;
p->next = q;
p = q;
return;
}
while (p->next != NULL)
{
LNode* temp = p;
p = p->next;
if (p->data == x) return;
if (p->data > x)
{
LNode* q = new LNode;
q->data = x;
q->next = p;
temp->next = q;
return;
}
}
LNode* q = new LNode;
q->data = x;
q->next = NULL;
p->next = q;
p = q;
return;
}
void OutputList(LinkList L)
{
LNode* p = L->next;
while (p != NULL) {
cout << p->data;
if (p->next != NULL)
cout << " ";
p = p->next;
}
}
int main ()
{
int n, x;
cin >> n;
LinkList L;
CreateList(L, n);
cin >> x;
InsertList(L, n, x);
OutputList(L);
return 0;
}
Student code
Write a personal feeling and clear
Worth collecting learning