struct Node {
char data;
Node* next;
};
Node* createList(char data[], int n) {
Node* head = (Node*) malloc(sizeof(Node));
Node* p = head;
for (int i = 0; i < n; i++) {
Node* node = (Node*) malloc(sizeof(Node));
node->data = data[i];
p->next = node;
p = p->next;
}
p->next = NULL;
return head;
}
void showList(Node* head) {
Node* p = head->next;
while (p != NULL) {
cout << p->data;
p = p->next;
}
cout << endl;
}
void myfree(Node* head) {
/*Node* p1=head->next;
Node* p2;
while(p1!=NULL){
cout<<p1->data;
p2=p1->next;
free(p1);
p1=p2;
}*/
Node* p1 = head;
Node* p2;
while (p1->next != NULL) {
if (p1 != head) {
cout << p1->data;
}
p2 = p1->next;
free(p1);
p1 = p2;
}
cout << p1->data;
free(p1);
}
int insert(Node* head, int pos, char e) {
int i = 0;
Node* p = head;
while (i != pos - 1 && p != NULL) {
i++;
p = p->next;
}
if (p == NULL) {
return -1;
}
Node* node = (Node*) malloc(sizeof(Node));
node->data = e;
Node* n = p->next;
p->next = node;
node->next = n;
return 1;
}
void del(Node* head,int pos)
{
int i=0;
Node* p=head;
while(i!=pos-1&&p!=NULL){
i++;
p=p->next;
}
Node* n=p->next;
p->next=p->next->next;
free(n);
}
//反转
void mreverse(Node* node)
{
if(node->next!=NULL)
{
Node* p1,*p2,*p3;
p1=node->next;
p2=p1->next;
p3=p2->next;
p1->next=NULL;
while(p3!=NULL){
p2->next=p1;
p1=p2;
p2=p3;
p3=p3->next;
}
p2->next=p1;
node->next=p2;
}
}
void mreverse2(Node* node)
{
Node* p1,*p2;
p1=node->next;
p2=p1->next;
while(p2!=NULL)
{
p1->next=p2->next;
p2->next=node->next;
node->next=p2;
p2=p1->next;
}
}
int main() {
char a[] = { 'a', 'b', 'c', 'd' };
Node* head = createList(a, 4);
insert(head, 1, 'g');
del(head,2);
mreverse(head);
mreverse2(head);
myfree(head);
return 0;
}