下午没事,看数据结构。想到自毕业以后,都没有写过这些东西了。写个链表基本操作,还没完全测试。
#include<iostream>
using namespace std;
/*Node 节点*/
struct Node
{
public:
Node(int d) { data = d; p = NULL; }
int data;
Node *p;
};
/*单链表*/
class Link {
private:
int length;
Node* head;
Node* tail;
public:
Link() { length = 0; head = NULL; tail = NULL; }
/*通过数组够造*/
Link(int *arr, int len) {
length = len;
Node * tmp = head;
for (int i = 0; i < len; i++){
Node* node = new Node(arr[i]);
if (i == 0){
head = node;
tmp = head;
continue;
}
tmp->p = node;
tmp = node;
}
tail = tmp;
}
/*打印链表*/
void printLink() {
Node * cur = head;
while (cur!=NULL){
cout << cur->data << " ";
cur = cur->p;
}
cout << endl;
}
/*链表逆序*/
void reverse() {
Node* c1, *c2, *c3;
c1 = head;
tail = head;
c2 = head->p;
while (c2 != NULL) { //c2 == NULL,说明单节点,无需逆序
if (c1 == head)
c1->p = NULL;
c3 = c2->p;
c2->p = c1;
if (c3->p == NULL) {
c3->p = c2;
head = c3;
break;
}
c1 = c2;
c2 = c3;
c3 = c3->p;
}
}
/*获得链表长度*/
int size() {
return length;
}
/*指定位置插入*/
void insert(int pos,int data) {
if (pos > length) {
tail->p = new Node(data);
}
else if (pos<=0){
Node* t = new Node(data);
t->p = head;
head = t;
}
else {
Node* new_node = new Node(data);
Node* cur = getNode(pos-1);
new_node->p = cur->p;
cur->p = new_node;
}
length++;
}
/*根据位置得到节点指针*/
Node* getNode(int pos) {
if (pos<0 || pos>length-1) return NULL;
int i = 0;
Node *cur = head;
while (i<pos){
i++;
cur = cur->p;
}
return cur;
}
/*删除指定位置*/
void del(int pos) {
Node* cur = getNode(pos);
Node* pre = getNode(pos - 1);
pre->p = cur->p;
delete cur;
}
/*清空链表*/
void clear() {
Node *tmp = head;
while (head != tail){
tmp = head;
head = head->p;
delete tmp;
}
delete head;
head = NULL;
length = 0;
}
/*更改指定位置的节点的值*/
void update(int pos, int new_date) {
Node* cur = getNode(pos);
cur->data = new_date;
}
/*查找指定位置的节点的值*/
void get(int pos) {
return getNode(pos)->data;
}
};
int main() {
int arr[] = { 5,7,9,4,0,1,8,3 };
Link link(arr, 8);
link.reverse();
link.insert(1, 2);
link.del(2);
link.update(7, 11);
link.printLink();
//link.clear();
//link.printLink();
system("pause");
}
507

被折叠的 条评论
为什么被折叠?



