单链表的一些基本操作

单链表是最基础的一种数据结构,在C/C++中的定义如下:

struct ListNode{
    ListNode *next;
    int val;
    ListNode(int x) : val(x), next(NULL) {}
};

平时在练习过程中经常遇到一些链表的操作问题。有些基础的操作经常会遗忘,还是进行一下总结吧。

1.复制链表

复制一个给定的链表,返回复制后链表的头结点,代码如下:

ListNode* copy(ListNode *pHead){
    if( pHead == NULL )
        return pHead;
    ListNode *newHead = new ListNode(pHead->val);
    ListNode *current = pHead->next;
    ListNode *newCurrent = newHead;
    while( current != NULL ){
        newCurrent->next = new ListNode(current->val);
        newCurrent = newCurrent->next;
        current = current->next;
    }
    return newHead;
}

2.反转链表

给一个链表的头结点,反转链表并返回反转后的头结点,代码如下:

ListNode* reverse(ListNode *pHead){
    if( pHead == NULL )
        return pHead;
    ListNode *currentNode = pHead;
    ListNode *preNode = NULL;
    ListNode *nextNode = NULL;
    while( currentNode != NULL ){
        nextNode = currentNode->next;
        currentNode->next = preNode;
        preNode = currentNode;
        currentNode = nextNode;
    }
    return preNode;
}

3.合并链表

给定链表A和链表B,合并这两个链表,使得A链表最后一个结点的下一个结点为B的头结点,返回合并后的链表头结点,代码如下:

ListNode* combine(ListNode *pHead1,ListNode *pHead2){
    ListNode *currentNode = pHead1;
    while( currentNode->next != NULL){
        currentNode = currentNode->next;
    }
    currentNode->next=pHead2;
    return pHead1;
}

4.单链表插入排序

给定一个单链表的头结点,使用插入排序算法排序链表,使得头结点的值最小。

ListNode* InsertionSort(ListNode* head){
    if(head == NULL || head->next == NULL)
            return head;
    ListNode* newHead = head;
    ListNode* processingNode = head->next;
    ListNode* nextNode = processingNode->next;
    newHead->next = NULL;
    while( processingNode != NULL ){
        ListNode* current = newHead;
        ListNode* pre = NULL;
        while( current != NULL && current->val < processingNode->val){
            pre = current;
            current = current->next;
        }
        if( pre == NULL ){
            newHead = processingNode;
            processingNode->next = current;
        }
        else{
            pre->next = processingNode;
            processingNode->next = current;
        }
        if( nextNode == NULL)
            break;
        processingNode = nextNode;
        nextNode = processingNode->next;
    }
    return newHead;
}

暂时就这些了,以后想到再添加。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值