ZBLOG

使用单链表的其他方法实现该代码:#ifndef NULL #define NULL 0 #endif #include using namespace std; //定义单链表结点结构 struct LNode { int data; LNode* next; LNode() {}; LNode(int e, LNode* n = NULL) :data(e), next(n) {}; }; //单链表list类创建 class List { protect...

以下是使用另一种方法实现该代码,使用带有尾指针的单链表:

”`cpp #ifndef NULL #define NULL 0 #endif

#include using namespace std;

//定义单链表结点结构 struct LNode {

int data;
LNode* next;
LNode() {};
LNode(int e, LNode* n = NULL) :data(e), next(n) {};

};

//单链表list类创建 class List { protected:

LNode* head; // 头指针
LNode* tail; // 尾指针
int _size;

public:

//构造函数
List()
{
    head = tail = new LNode();
    _size = 0;
}

//析构函数
~List() {
	LNode* p = head;
	while (head)
	{
		p = p->next;
		delete head;
		head = p;
	}
}

void insert(int& e)
{
    _size++;
    tail->next = new LNode(e);
    tail = tail->next;
}

void insert(int index, int a)
{
    if (index < 1 || index > _size + 1)
    {
        return; // 无效的插入位置,直接返回
    }

    _size++;

    LNode* p = head;

    for (int i = 1; i < index; i++)
    {
        p = p->next;
    }

    p->next = new LNode(a, p->next);

    if (p == tail) // 更新尾指针位置
        tail = p->next;

}

void print_L()
{
    LNode* p = head->next;
    while (p != NULL)
    {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
}

int change()
{
    int x, y;
    cin >> x >> y;
    if (x<0 || x>_size || y<0 || y>_size)
    {
        cout << "error" << endl;
        return -1;
    }

    LNode* px = head; // 要交换的节点 x 的前一个节点
    LNode* py = head; // 要交换的节点 y 的前一个节点

    for (int i = 0; i < x - 1; i++)
    {
        px = px->next;
    }

    for (int j = 0; j < y - 1; j++)
    {
        py = py->next;
    }

    LNode* tmp_x_next = px->next;

    px->next = py->next;

    py->next = tmp_x_next;

    LNode* tmp_y_next = px->next->next;

     px->next->next= tmp_x_next -> next;

      tmp_x_next -> next= tmp_y_next;





   return 0;
}

};

int main() {

List LB;
int n, a;
cin >> n;

for (int i = 0; i < n; i++)
{
    cin >> a;
    LB.insert(i + 1, a);
}

LB.print_L();

int t;
cin >> t;

for (int i = 0; i < t; i++)
{
	int a = LB.change();
	if (a == -1)
		continue;
	LB.print_L();
}

} “`


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9584

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?