码迷,mamicode.com
首页 > 其他好文 > 详细

逆序单链表

时间:2014-06-09 17:50:43      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:c   class   blog   code   a   ext   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <iostream>
using namespace std;
 
struct Node
{
    Node *next;
    int elem;
};
 
void creatList(Node* &head)
{
    head = new Node;
    int elem;
    cin>>elem;
    head->elem = elem;
    Node *p = head;
    while(cin>>elem&&elem)
    {
        Node *q = new Node;
        q->elem = elem;
        p->next = q;
        p = p->next;
    }
    p->next = NULL;
}
void printList(Node* &head)
{
    cout<<head->elem<<" ";
    Node *p = head->next;
    while(p)
    {
        cout<<p->elem<<" ";
        p = p->next;
    }
    cout<<endl;
}
void removeX(Node* &head,int x)
{
    Node *p;
    if(head == NULL)
        return;
    else if(head->elem == x)
    {
        p = head;
        head = head->next;
        free(p);
        removeX(head, x);
    }
    else
        removeX(head->next, x);
}
 
Node* getElem(Node* head,int i)
{
    int j = 1;
    Node *p = head;
    if(head==NULL)
        return head;
    while(p&&j<i)
    {
        j++;
        p = p->next;
    }
    return p;
}
void insertNode(Node* &head,int i,int data)
{
    Node* p = getElem(head, i-1);
    Node* q = new Node;
    q->elem = data;
    q ->next = p ->next;
    p ->next = q;
}
void deleteNode(Node* &head,int i)
{
    Node* p = getElem(head, i-1);
    Node* q = p->next;
    p->next = q->next;
    free(q);
}
void reverseList(Node* &head)
{
    if(head == NULL||head ->next == NULL)
        return ;
    Node *pre = head;
    Node *cur = head->next;
    Node *nex = NULL;
    while(cur)
    {
        nex = cur -> next;
        cur ->next = pre;
        pre = cur;
        cur = nex;
    }
    head->next = NULL;
    head = pre;
}
int main()
{
    Node *p;
    creatList(p);
    printList(p);
    //removeX(p, 4);
    insertNode(p, 2, 100);
    printList(p);
    cout<<getElem(p, 3)->elem<<endl;
    deleteNode(p, 2);
    printList(p);
    reverseList(p);
    printList(p);
    return 0;
}

 

逆序单链表,布布扣,bubuko.com

逆序单链表

标签:c   class   blog   code   a   ext   

原文地址:http://www.cnblogs.com/cliviazhou/p/3777510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!