单链表是最基础的一种数据结构,在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;
}
暂时就这些了,以后想到再添加。