Skip to content

Commit 5a64cfa

Browse files
committed
Linklist
Signed-off-by: XuYuanhui <981424785@qq.com>
1 parent 7db03d7 commit 5a64cfa

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
#include <iostream>
2+
#include <stdlib.h>
3+
4+
using namespace std;
5+
6+
typedef struct Node {
7+
int data;
8+
struct Node *pNext;
9+
} NODE, *pNODE;
10+
11+
12+
pNODE CreatLinkList(void) {
13+
int i, length, data;
14+
pNODE p_new = NULL, pTail = NULL;
15+
pNODE pHead = (pNODE)malloc(sizeof(NODE));
16+
17+
if(pHead == NULL) {
18+
cout << "error" << endl;
19+
return NULL;
20+
}
21+
pHead->data = 0;
22+
pHead->pNext = NULL;
23+
pTail = pHead;
24+
25+
cout << "input length" << endl;
26+
cin >> length;
27+
28+
for (i = 1; i < length; i++) {
29+
p_new = (pNODE)malloc(sizeof(NODE));
30+
if(p_new == NULL) {
31+
cout << "error" << endl;
32+
return NULL;
33+
}
34+
35+
cout << "input data for " << i << endl;
36+
cin >> data;
37+
p_new->data = data;
38+
p_new->pNext = NULL;
39+
pTail->pNext = p_new;
40+
pTail = p_new;
41+
}
42+
return pHead;
43+
}
44+
45+
void OutputLinkList(pNODE p_node) {
46+
pNODE o_node = p_node;
47+
while (o_node != NULL) {
48+
cout << "node data " << o_node->data << endl;
49+
o_node = o_node->pNext;
50+
}
51+
cout << "\n" << endl;
52+
}
53+
54+
bool IsEmpty(pNODE p_node) {
55+
pNODE e_node = p_node->pNext;
56+
if (e_node ==NULL) {
57+
return true;
58+
}
59+
return false;
60+
}
61+
62+
// Á´±í·´×ª
63+
64+
pNODE ReverseLinkList(pNODE p_node) {
65+
pNODE pHead, p, q;
66+
pHead = p_node;
67+
if (pHead->pNext == NULL) {
68+
cout << "NONE" << endl;
69+
return NULL;
70+
} else if(pHead->pNext != NULL && pHead->pNext->pNext != NULL) {
71+
p = pHead->pNext;
72+
q = pHead->pNext->pNext;
73+
} else {
74+
return pHead;
75+
}
76+
77+
while (p != NULL && q != NULL) {
78+
pNODE temp;
79+
temp = q->pNext;
80+
q->pNext = p;
81+
p = q;
82+
q = temp;
83+
}
84+
pHead->pNext->pNext = NULL;
85+
pHead->pNext = p;
86+
return pHead;
87+
}
88+
89+
int Backward_k (pNODE p_node, int k) {
90+
pNODE p_fast = p_node;
91+
pNODE p_slow = p_node;
92+
int number = 0;
93+
while (p_fast != NULL) {
94+
++number;
95+
if (number < k) {
96+
p_fast = p_fast->pNext;
97+
} else {
98+
p_fast = p_fast->pNext;
99+
if (p_fast == NULL)
100+
return p_slow->data;
101+
p_slow = p_slow->pNext;
102+
}
103+
}
104+
return 0;
105+
}
106+
107+
int main()
108+
{
109+
cout << "Hello world!" << endl;
110+
pNODE head = NULL, re_head = NULL;
111+
int k_data = 0;
112+
head = CreatLinkList();
113+
OutputLinkList(head);
114+
re_head = ReverseLinkList(head);
115+
OutputLinkList(re_head);
116+
k_data = Backward_k(re_head, 4);
117+
cout << "backwards k is " << k_data << endl;
118+
return 0;
119+
}

0 commit comments

Comments
 (0)