【LeetCode】22.Linked List — Design Linked List 设计链表(链表的定义、初始化及插入删除操作)...

Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: val and nextval is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.

Implement these functions in your linked list class:

  • get(index) : Get the value of the index-th node in the linked list. If the index is invalid, return -1.
  • addAtHead(val) : Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
  • addAtTail(val) : Append a node of value val to the last element of the linked list.
  • addAtIndex(index, val) : Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
  • deleteAtIndex(index) : Delete the index-th node in the linked list, if the index is valid.

Example:

MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1, 2);  // linked list becomes 1->2->3
linkedList.get(1);            // returns 2
linkedList.deleteAtIndex(1);  // now the linked list is 1->3
linkedList.get(1);            // returns 3

Note:

  • All values will be in the range of [1, 1000].
  • The number of operations will be in the range of [1, 1000].
  • Please do not use the built-in LinkedList library.

这里给出链表的类定义,包括结点的定义,插入删除操作。

// Definition for singly-linked list.
struct Node {
    int val;
    Node *next;
//    Node(int x) :val(x), next(NULL) {} //结构体构造函数,仅限C++内使用
};

class MyLinkedList {
    Node *head;    //链表头
    Node *tail;    //链表尾 
    int length;    //链表长度
public:
    /** Initialize your data structure here. */
    MyLinkedList() {  //类默认构造函数,不显示声明时提供初始化操作
        head = NULL;
        tail = NULL;
        length = 0; 
    }

    /** Get the value of the index-th Node in the linked list. If the index is invalid, return -1. */
    int get(int index) {  //获取指定下标的值
        Node*p = head;
        if (index < 0 || index >= length) return -1;
        for (int i = 0; i<index; i++) //从头结点开始遍历,找到指定的值
        {
            p = p->next;
        }
        return p->val;
    }

    /** Add a Node of value val before the first element of the linked list. After the insertion, the new Node will be the first Node of the linked list. */
    void addAtHead(int val) {  //头部插入,需要定义新的结点,更新length值
        Node*Add1 = new Node;  //定义构造函数后,则初始化方式变为:Node*Add1= new Node(val);
        Add1->val = val;
        Add1->next = head;
        head = Add1;
        length++;
        if (length == 1) tail = head;

    }

    /** Append a Node of value val to the last element of the linked list. */
    void addAtTail(int val) { //尾部插入,定义新结点,判断特殊情况,更新length值
        Node*Add2 = new Node;
        Add2->val = val;
        if (tail != NULL)     tail->next = Add2;
        tail = Add2;
        length++;
        if (length == 1) head = tail;
    }

    /** Add a Node of value val before the index-th Node in the linked list. If index equals to the length of linked list, the Node will be appended to the end of linked list. If index is greater than the length, the Node will not be inserted. */
    void addAtIndex(int index, int val) { //在特定下标前插入结点,分情况讨论,更新length的值
        if (index > length) return;
        if (index == length) {
            addAtTail(val);
            return;
        }
        if (index <= 0) {
            addAtHead(val);
            return;
        }
        Node*p = head;
        for (int i = 0; i < index - 1; i++)
        {
            p = p->next;
        }
        Node*Add3 = new Node;
        Add3->val = val;
        Add3->next = p->next;
        p->next = Add3;
        length++;
    }

    /** Delete the index-th Node in the linked list, if the index is valid. */
    void deleteAtIndex(int index) { //删除指定下标结点
        if (index >= length || index<0) return;
        Node*p = head;
        if (index == 0) {
            head = head->next;
            delete p;
            length--;
            return;
        }
        for (int i = 0; i < index - 1; i++)
        {
            p = p->next;
        }
        Node*Delete = p->next; //要删除的节点
        p->next = Delete->next;
        if (tail == Delete)tail = p;
        delete Delete;
        length--;
    }
};

/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList* obj = new MyLinkedList();
* int param_1 = obj->get(index);
* obj->addAtHead(val);
* obj->addAtTail(val);
* obj->addAtIndex(index,val);
* obj->deleteAtIndex(index);
*/

 

转载于:https://www.cnblogs.com/hu-19941213/p/11062700.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【问题描述】 请设计一个链表类,实现链表初始化插入删除和打印操作。 节点的定义如下: typedef int elementType; typedef struct node { elementType data; node* next; } LList, *PList; 链表类的定义及要求如下: class linkedList { public: linkedList();//构造函数 virtual ~linkedList();//析构函数,注意要链表中所有节点的资源 void insert( int value );//警告:必须初始化才能使用! bool initiate();//初始化链表,使用new操作创建头结点。如果创建失败,则返回false,否则返回true bool isEmpty();//判断单链表是否为空 //删除链表中第pos个元素结点,并将删除的节点的值存在value中。 //注意:如果链表为空、删除位置大于链表长度、以及删除位置为0的情况,需要终止删除并输出相应信息 bool remove( int pos, int& value ); void print();//顺序打印单链表,如果是单链表为空,则输出 Empty int Length();//返回单链表长度。如果是单链表为空,则返回-1 private: LList *head; int len; }; main函数: int main(int argc, char* argv[]) { linkedList L1; int n; int val; //初始化链表 if(!L1.initiate()) return 0; cin>>n;//输入链表中数据个数 for(int i=0; i<n; i++) //输入n个数,并插入链表 { cin>>val; L1.insert(val); } cout << "Origin Length:" << L1.Length() << endl;//输出链表长度 cout << "data:" ; L1.print();//打印链表 cin>>n;//输入需要删除的数据的位置 if (L1.remove(n,val)) { //删除位置n的数据,并将删除的数据值放在val中 cout<<"Delete the data at position("<<n<<"):"<<val<<endl; cout<< "New Length:" << L1.Length()<< endl;//输出链表长度 cout<< "data:" ; L1.print();//打印链表 } return 0; } 【输入形式】 输入包括3行。 第一行是链表元素个数n。第二行为n个元素的值。第三行为拟删除的数据位置。 【输出形式】 输出格式不固定。具体参见样例。 【样例输入1】 4 1 2 3 4 2 【样例输出1】 Origin Length:4 data:1 2 3 4 Delete the data at position(2):2 New Length:3 data:1 3 4 【样例输入2】 2 100 -1 3 【样例输出2】 Origin Length:2 data:100 -1 pos > len, failed 【样例输入3】 8 8 7 6 5 4 3 2 1 0 【样例输出3】 Origin Length:8 data:8 7 6 5 4 3 2 1 pos <= 0, failed

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值