链表操作那点呵呵哒的事

       要把1--->2--->3--->4--->5--->6转为1--->6--->2--->5--->3--->4.

       又是周末, 又是小雨, 写着玩下, 没啥技术含量, 纯当是玩游戏罢了, 这种低级的游戏搞多了, 伤身, 就跟沉迷于王者荣耀一样, 不是啥好东西:

#include <iostream>
#include <cassert>
using namespace std;


typedef struct node
{
	int data;
	struct node *next;
}Node;


void print(Node *pHead)
{
	assert(pHead);
 
	pHead = pHead->next;
	while(pHead != NULL)
	{
		cout << pHead->data << " ";
		pHead = pHead->next;
	}
 
	cout << " " << endl;
}


void splitList(Node *head, Node* &head1, Node * &head2) // 这里必须用引用,否则呵呵哒
{
	assert(head);
	int iLen = head->data;
	int iMid = iLen / 2;
	head1 = head;
	Node *p_prior = head;
	Node *p = head->next;
	int i = 0;
	while(p && i++ < iMid)  // 漏了++的是SB
	{
		p_prior = p;
		p = p->next;
	}

	p_prior->next = NULL;
	head1->data = iMid;


	head2 = (Node *)malloc(sizeof(Node));
	assert(head2);
	head2->data = iLen - iMid;
	head2->next = p;
}

 
Node *reverseList(Node *pHead)
{
    assert(NULL != pHead);
 
    Node *p1 = pHead->next;
    Node *p2 = p1;
    pHead->next = NULL;
    
    while(p1 != NULL)
    {
        p2 = p1;
        p1 = p1->next;
        
        p2->next = pHead->next;
        pHead->next = p2;
    }
    
    return pHead;
}


Node *combineLink(Node *head1, Node *head2)
{
	assert(head1 && head2);
	Node *p1_prior = head1;
	Node *p2_prior = head2;
	Node *p1 = p1_prior->next;
	Node *p2 = p2_prior->next;

	int totalLen = head1->data + head2->data;

	while(p1 && p2) // 其中无需改变头结点中的链表长度字段data
	{
		// 预存
		p2_prior->next = p2->next;

		// 插入
		p2->next = p1->next;
		p1->next = p2;
		
		// 调整关系
		p1 = p2->next;
		p1_prior = p2;
		p2 = p2_prior->next;
	}
	
	p1_prior->next = p2_prior->next;
	head1->data = totalLen;

	free(p2_prior);

	return head1;
}


int main()
{
	Node n, n1, n2, n3, n4, n5, n6;
	n.data = 6;
	n1.data = 1;
	n2.data = 2;
	n3.data = 3;
	n4.data = 4;
	n5.data = 5;
	n6.data = 6;
 
	n.next = &n1;
	n1.next = &n2;
	n2.next = &n3;
	n3.next = &n4;
	n4.next = &n5;
	n5.next = &n6;
	n6.next = NULL;
 

	print(&n);
	Node *head1 = NULL;
	Node *head2 = NULL;
		
	splitList(&n, head1, head2);
	print(head1);
	print(head2);


	head2 = reverseList(head2);
	print(head2);

	Node *head = combineLink(head1, head2);
	print(head);

	return 0;
}

        结果:

1 2 3 4 5 6
1 2 3
4 5 6
6 5 4
1 6 2 5 3 4

         不多说。

猜你喜欢

转载自blog.csdn.net/stpeace/article/details/81584859