C++——数据结构之链表

直接上例子

int main()
{
    int a1[]={3,4,2};
    int a2[]={4,6,5};

    Listnode *head=NULL,*temp;
    head=(Listnode*)malloc(sizeof(Listnode));//头节点
    head->next=NULL;
    /*1.new node in head->next,head on the botom 
    for (int i=0;i<3;i++)
    {
        temp=(Listnode*)malloc(sizeof(Listnode));
        temp->val=a1[i];

        temp->next=head->next;//先把上一次插入的链表打断,接入新插入节点的后面
        head->next=temp;//然后把链条接入头节点的下面。于是:每一个新节点都插入到头节点之后,于是倒序了
}*/ 

/*2. */

Listnode *r;
r
=head; //地址
for (int i=0;i<3;i++)
{
  temp
=(Listnode*)malloc(sizeof(Listnode));
  temp
->val=a1[i];
  r
->next=temp; //每一个新节点都插入到了原来链条的最后,并且链条向后走了一步
  r
=temp; //更新最后一个节点
}
r
->next=NULL; //把最后节点指向NULL

temp
=head->next;//将链表移到首结点开始打印
while (temp)
{
  cout
<<"->"<<temp->val<<endl;
  temp
=temp->next;
}
return 0;
}

 

 

1.通过数组建链表

int nums2[] = {1,3,5};
////////////////////1.
ListNode* head2=new ListNode(nums2[0]);
r=head2;
for(int i=1;i<sizeof(nums2)/sizeof(int);i++)
{
    r->next=new ListNode(nums2[i]);
    r=r->next;
}
/////////////2.
ListNode* createList(int a[], int n)
{
    ListNode *head=NULL, *p=NULL;
    for(int i=0; i<n; i++){
        if (head == NULL){
            head = p = new ListNode(a[i]);
        }else{
            p->next = new ListNode(a[i]);
            p = p->next;
        }
    }
    return head;
}
ListNode* p1 = createList(nums2, sizeof(nums2)/sizeof(int));

 

2.链表反转

ListNode* reverse(ListNode* first,ListNode* last)
    {
        ListNode* prev=NULL;
        if(!first || !last) return prev;

        ListNode* tmp=NULL;
        while(first && first!=last){
            tmp=first->next;
            first->next=prev;
            prev=first;
            first=tmp;
        }
        last->next=prev;
        return last;
    }

 

原文链接: https://www.cnblogs.com/yrm1160029237/p/11055505.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++——数据结构之链表

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/297104

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午6:26
下一篇 2023年2月15日 下午6:26

相关推荐