链表是数据结构中最基本的,也是非常经典的,在面试笔试中也是经常出现的题,但是万变不离其宗,只要掌握了基本的操作,一起尽在掌控。
特别要注意的一点是处理时千万要把是否为头进行判断,做为一个特例,或者建立链表就先固定建立一个表头,这样代码就没这么多判断了。
#include<iostream>
using namespace std;
struct Node{
int val;
Node *next;
Node(int v){ val = v; next = NULL; }
};
class List
{
private:
Node * head;
int size;
public:
//构造函数
List(){
head = NULL;
size = 0;
};
//析构函数
~List(){
Node *current = head;
Node *cnext = head->next;
while (current){
delete current;
current = cnext;
if (cnext)
cnext = cnext->next;
}
}
//新建链表
void createList(){
int v = 0;
Node *n1 = NULL;
Node *current = NULL;
cout << "请输入整数构建链表:" << endl;
while (cin >> v){
if (!head){
head = new Node(v);
current = head;
size = 1;
continue;
}
n1 = new Node(v);
current->next = n1;
current = current->next;
++size;
}
}
//判断是否为空链表
bool isEmpty(){
if (head)
return false;
return true;
}
//插入一个节点,遇到的第一个大于节点值之前
void insertNode(int val){
//empty
if (isEmpty()){
head = new Node(val);
size = 1;
return;
}
if (head->val > val){
Node *temp = head;
head = new Node(val);
head->next = temp;
return;
}
Node *current = head->next;
Node *previous = head;
while (current && (current->val < val)){
previous = current;
current = current->next;
}
Node *temp = new Node(val);
previous->next = temp;
temp->next = current;
++size;
}
//打印链表
void printList(){
Node *current = head;
while (current){
cout << current->val << ' ';
current = current->next;
}
cout << endl;
}
//删除一个节点
void deleteNode(int val){
Node *current = head;
Node *previous = head;
while (current){
if (current->val == val){
break;
}
previous = current;
current = current->next;
}
if (!current){
cout << "Node does not exist!" << endl;
return;
}
if (current == head){
head = current->next;
}
else{
previous->next = current->next;
}
delete current;
--size;
cout << "Node deletes successfully!" << endl;
}
//列表增序排序,插入排序
void sortList(){
if (isEmpty())
return;
Node *current = head->next;
Node *previous = head;
Node *ln = head;
Node *pln = head;
Node *temp;
while (current){
ln = head;
pln = head;
while (ln != current && ln->val < current->val){
pln = ln;
ln = ln->next;
}
if (ln != current){
temp = current;
previous->next = temp->next;
if (ln == head){
head = temp;
head->next = ln;
}
else{
pln->next = temp;
temp->next = ln;
}
}
previous = current;
current = current->next;
}
}
};
int main(){
List l;
l.createList();
l.printList();
l.insertNode(3);
l.printList();
l.deleteNode(3);
l.printList();
l.sortList();
l.printList();
return 0;
}
//链表逆置
void reverse()
{
if (isEmpty() || getSize() == 1)
return;
Node *previous = head;
Node *current = head->next;
if (!current->next){
head->next = NULL;
head = current;
head->next = previous;
printList();
return;
}
Node *next = current->next;
head->next = NULL;
while (next){
current->next = previous;
previous = current;
current = next;
next = current->next;
}
head = current;
head->next = previous;
printList();
}